2013-03-05 87 views
0

所以我試圖通過他們的類別來計算我的集合中的模型。集合的骨幹定製屬性

這是我的代碼:

App.Collections.channls = Backbone.Collection.extend({ 
    model: App.Models.Channel, 
    catCount: new Array(), 

    initialize: function() { 
     this.bind('add', this.onModelAddedd, this); 
    }, 

    onModelAdded: function(model, collection) { 
     if (this.catCount[model.get('category_id')] == undefined) { 
      this.catCount[model.get('category_id')] = 0; 
     } 
     this.catCount[model.get('category_id')]++; 
    }, 

    returnCount: function() { return this.catCount } 
}); 

我初始化這個集合了幾次。

問題是,當我得到該集合的catCount屬性時,該數組就像一個全局變量。因此,它不僅計算自己的集合實例中的模型,而且還計算通過所有集合實例添加的所有模型。

任何人知道如何使一個集合的屬性只計入它自己的實例嗎?

+0

你爲什麼初始化這個集合了幾次初始化?意思是多次綁定添加事件。 – 2013-03-05 10:03:51

+0

我有需要分離的數據,但具有相同的結構(如此相同的模型和集合) – user2091464 2013-03-05 12:25:04

+2

您可以通過創建多個模型或集合實例來使用相同的結構。 – 2013-03-05 12:31:29

回答

1

也許你需要移動catCount來初始化函數?

initialize: function() { 
    this.catCount= new Array(); 
    this.bind('add', this.onModelAddedd, this); 
} 

所以它會被每一個新的集合實例

+0

是啊,這似乎解決了它!謝謝 – user2091464 2013-03-06 10:36:02