All Projects → ianstormtaylor → backbone-inheritance

ianstormtaylor / backbone-inheritance

Licence: other
(I no longer use Backbone, but feel free to check this plugin out. The code is pretty straightforward.) A Backbone.js mixin that lets Views inherit properties from their parents.

Programming Languages

javascript
184084 projects - #8 most used programming language

Backbone Inheritance

A mixin for Backbone that lets instances inherit properties up the prototype chain by combining instead of overwriting. So arrays will be unioned, objects extended, and strings concatenated. You can set which individual properties you'd like to inherit.

Calling the mixin

Backbone Inheritance will be available under Backbone.mixin.inheritance when not using AMD, or it will just return the mixin itself if you are using AMD.

To use the Backbone Inheritance mixin, you need to mix it into whichever Backbone class you'd like to have inheritance:

Backbone.mixin.inheritance.call(Backbone.View);

More likely, you'll want to mix it into your BaseView:

Backbone.mixin.inheritance.call(BaseView);

Then you define the properties you want to inherit in the inherits when you extend the view:

var BaseView = Backbone.View.extend({
    inherits : ['className', 'options'];
});
Backbone.mixin.inheritance.call(BaseView);

Once you apply the mixin, your instances will inherit properties up the prototype chain.

A quick example

If you have Cat and AngryCat, if you only wanted to add a single option to this.options you'd have to re-copy all of the previously defined options as well:

var Cat = Backbone.View.extend({
    options : {
        furColor : 'black',
        age      : 4,
        name     : 'Felix',
        weight   : 8.3

    }
});

var AngryCat = Cat.extend({
    options : {
        emotionalState : 'angry!', // The new one!
        furColor       : 'black', 
        age            : 4,
        name           : 'Felix',
        weight         : 8.3
    }
});

But with the Backbone Inheritance mixin, the other properties are automatically inherited for you:

var Cat = Backbone.View.extend({
    options : {
        furColor : 'black',
        age      : 4,
        name     : 'Felix',
        weight   : 8.3
    }
});

var AngryCat = Cat.extend({
    options : {
        emotionalState : 'angry!' // That's it!
    }
});
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].