In Backbone.js how can I get Model superclass defaults to act as defaults for subclasses?

狂风中的少年 提交于 2019-12-10 03:14:40

问题


I have a class that defines some defaults, and a subclass that defines some defaults. But when I create an instance of the subclass it only looks at the local defaults and does not merge its defaults with those of the parent. Is there any simple way to do this without explicitly merging the local defaults with the parent defaults in the initialize function of every subclass?

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

var ExtendedInventory = Inventory.extend({
    defaults: {
        rabbit: 25
    }
});

var ei = new ExtendedInventory({});
console.log(ei.attributes);

This outputs:

{rabbit: 25}

Not what I want:

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

回答1:


You can't do it like that. You will have to do it after the subclass

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

Put this after your model definition.



来源:https://stackoverflow.com/questions/6505873/in-backbone-js-how-can-i-get-model-superclass-defaults-to-act-as-defaults-for-su

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!