函数:为什么主干集合中的所有子集合都在更新

function: why are all children updating in this backbone collection?

本文关键字:子集合 更新 为什么 集合 函数      更新时间:2023-09-26

我有一个Backbone collectionView,其中包含x数量的公司。我还收集了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));
    },

您的Company模型如何定义资产属性?如果它被定义为模型的直接属性或在默认的对象中,那么您将得到您所描述的行为。如果是这种情况,将其移动到默认的方法,例如

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