Extending the defaults of a Model superclass in Ba

2019-01-22 06:04发布

I would like to pose this as a question to this answer but I can't seem to do so, I apologize.

Extending the defaults for the subclass are reflected in the superclass. This seems to defeat the purpose and I'm more apt to explicitly list the superclass' defaults in the subclass to get the structure I'm looking for.

var Inventory = Backbone.Model.extend({
    defaults: {
        cat: 3,
        dog: 5
    }
});

var ExtendedInventory = Inventory.extend({
});

_.extend(ExtendedInventory.prototype.defaults, {rabbit: 25});

var i = new Inventory();
var ei = new ExtendedInventory();
console.log(i.attributes);
console.log(ei.attributes);

This outputs:

{cat: 3, dog: 5, rabbit: 25}
{cat: 3, dog: 5, rabbit: 25}

Not what I (nor, I assume, the op) want:

{cat: 3, dog: 5}
{cat: 3, dog: 5, rabbit: 25}

7条回答
聊天终结者
2楼-- · 2019-01-22 06:30

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/

查看更多
登录 后发表回答