我有一个模型,它包含一个带有一些Backbone.Collections的默认对象。我不知道这是不是最优雅的解决方案,但它目前满足了我的需求。但是,当创建模型的新实例时,不会重置集合,但会添加新模型。默认值不应该自动重置吗?现在我必须在initialize函数中设置myColls。
var MyModel = Backbone.Model.extend({
defaults: {
'someProp': '',
'myColls': {
'first': new Backbone.Collection(),
'second': new Backbone.Collection(),
'third': new Backbone.Collection()
}
},
initialize: function() {
// This does reset myColls:
this.set('myColls', {
'first': new Backbone.Collection(),
'second': new Backbone.Collection(),
'third': new Backbone.Collection()
});
}
}发布于 2013-04-16 15:44:55
正如Model.defaults主干文档中所述
请记住,在JavaScript中,对象是通过引用传递的,所以如果包含一个对象作为默认值,它将在所有实例之间共享。相反,将defaults定义为函数。
所以,
var MyModel = Backbone.Model.extend({
defaults: function() {
return {
'someProp': '',
'myColls': {
'first': new Backbone.Collection(),
'second': new Backbone.Collection(),
'third': new Backbone.Collection()
}
};
},
initialize: function() {
}
});https://stackoverflow.com/questions/16031354
复制相似问题