功能:为什么所有孩子都在这个骨干集合中更新?

时间:2015-05-31 14:46:09

标签: javascript backbone.js collections

我有一个拥有x公司数量的Backbone collectionView。 我还收集了x种产品。

我想获得一个随机产品并将其添加到"资产"在一家随机公司。 (公司从this.getRandomCompany()函数返回)

但是当我运行以下功能时,所有公司的孩子都会同时使用相同的产品进行更新。

console.log(randomCompany)的结果是一个孩子,为什么所有孩子都在更新?

   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));
    },

1 个答案:

答案 0 :(得分:2)

贵公司如何定义资产属性?如果它被定义为模型的直接属性或默认的对象,那么您将获得您正在描述的行为。如果是这种情况,请将其移至默认方法,例如

var Company = Backbone.Model.extend({
    ...
    defaults: function() {
        return {
            assets: []
        }
    },
    ...
});