在 Backbone.js 中,如何让模型超类默认值充当子类的默认值?
我有一个定义一些默认值的类和一个定义一些默认值的子类。但是,当我创建子类的实例时,它只查看本地默认值,不会将其默认值与父类的默认值合并。有没有简单的方法可以做到这一点,而无需在每个子类的 initialize
函数中显式地将本地默认值与父默认值合并?
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);
这输出:
{rabbit: 25}
不是我想要的:
{cat: 3, dog: 5, rabbit: 25}
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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能那样做。您必须在子类之后执行此操作
将其放在模型定义之后。
You can't do it like that. You will have to do it after the subclass
Put this after your model definition.