Search code examples
javascriptinheritancebackbone.js

Inherit backbone attributes from parent model


If i have this model:

var myParentModel = Backbone.Model.extend({
   defaults:{ parent1: null,
              parent2: null}
)};

and i have another model:

var myModel = myParentModel.extend({
   defaults: {child1: null,
              child2: null}
)};

if i instanciate a new myModel:

var mymodel = new myModel({child1: 'mychild1'});

In the attributes property i only have set to default the child2 property, how is the implementation to inherit the parents property of the parent model?


Solution

  • In github there is an interesting post with this issue, the solution that i was implement is this:

    myModel.prototype.defaults = 
        _.extend({
            child1: null,
                    child2: null
        }, myParentModel.prototype.defaults, 
           myModel.prototype.defaults);
    

    With the underscore function: extend, we have a new object defaults with the parent and child prototype, this is a good solution for multiple inherit