功能:为什么所有children都在这个backbonecollection中更新?
function: why are all children updating in this backbone collection?
我有一个 Backbone collection视图,其中包含 x 家公司。
我还有 collection x 数量的产品。
我想获得一个随机产品并将其添加到随机公司的 "assets" 列表中。 (公司从 this.getRandomCompany()
函数返回)
但是当我 运行 以下功能时,所有公司 children 都会同时更新相同的产品。
console.log(randomCompany)
的结果是一个child,为什么都在children更新?
addProduct: function() {
var randomProductIndex = Math.round(Math.random() * (this.products.length));
var randomProduct = new App.CompanyModule.Product({
"name": this.products[randomProductIndex]
});
this.getRandomCompany(_.bind(function(randomCompany) {
console.log(randomCompany);
randomCompany.model.get("assets").add(randomProduct);
this.render();
}, this));
},
您的公司模型如何定义资产 属性?如果它被定义为模型的直接 属性 或在默认 对象 中,那么您将获得您所描述的行为。如果是这种情况,请将其移至默认 方法 ,例如
var Company = Backbone.Model.extend({
...
defaults: function() {
return {
assets: []
}
},
...
});
我有一个 Backbone collection视图,其中包含 x 家公司。 我还有 collection x 数量的产品。
我想获得一个随机产品并将其添加到随机公司的 "assets" 列表中。 (公司从 this.getRandomCompany()
函数返回)
但是当我 运行 以下功能时,所有公司 children 都会同时更新相同的产品。
console.log(randomCompany)
的结果是一个child,为什么都在children更新?
addProduct: function() {
var randomProductIndex = Math.round(Math.random() * (this.products.length));
var randomProduct = new App.CompanyModule.Product({
"name": this.products[randomProductIndex]
});
this.getRandomCompany(_.bind(function(randomCompany) {
console.log(randomCompany);
randomCompany.model.get("assets").add(randomProduct);
this.render();
}, this));
},
您的公司模型如何定义资产 属性?如果它被定义为模型的直接 属性 或在默认 对象 中,那么您将获得您所描述的行为。如果是这种情况,请将其移至默认 方法 ,例如
var Company = Backbone.Model.extend({
...
defaults: function() {
return {
assets: []
}
},
...
});