Extending the defaults of a Model superclass in Backbone.js Extending the defaults of a Model superclass in Backbone.js javascript javascript

Extending the defaults of a Model superclass in Backbone.js


The problem is that Inventory.prototype.defaults and Extended.prototype.defaults has the same reference, because you have not override the reference.

So you can do this in 2 ways, maybe more but i only found this 2:

Edit: The first example is incorrect (see comments); please refer to the second.

var ExtendedInventory = Inventory.extend({    defaults: {        rabit:25    }});_.extend(ExtendedInventory.prototype.defaults, Inventory.prototype.defaults);

or

var ExtendedInventory = Inventory.extend({    defaults: _.extend({},Inventory.prototype.defaults,         {rabit:25}    )});

I think the first looks cleaner.


I think the best way to solve it is to use underscore.js's _.defaults method. This will allow you to override default values in your Model subclass:

_.defaults(ExtendedInventory.prototype.defaults,            Inventory.prototype.defaults);

See this example:

http://jsfiddle.net/mattfreer/xLK5D/


As an extension of JCorcuera's answer, if your base class uses (or may use) a function to define defaults then this will work nicely:

   defaults: function() {                                          return _.extend( _.result(Slot.prototype, 'defaults'),{         kind_id: 6,                                         otherthing: 'yello'         // add in your extended defaults here                                   })}                                                      

the key bit being the use of a funciton in the child defaults method and _.result() docs