Javascript 集合的主干自定义属性

Javascript 集合的主干自定义属性,javascript,backbone.js,Javascript,Backbone.js,所以我试着按我收藏的模特的类别来统计他们 这是我的代码: App.Collections.channls=Backbone.Collection.extend({ 型号:App.Models.Channel, catCount:新数组(), 初始化:函数(){ this.bind('add',this.onModelAddedd,this); }, onModelAdded:函数(模型、集合){ if(this.catCount[model.get('category_id')]==未定义){

所以我试着按我收藏的模特的类别来统计他们

这是我的代码:

App.Collections.channls=Backbone.Collection.extend({
型号:App.Models.Channel,
catCount:新数组(),
初始化:函数(){
this.bind('add',this.onModelAddedd,this);
},
onModelAdded:函数(模型、集合){
if(this.catCount[model.get('category_id')]==未定义){
this.catCount[model.get('category_id')]=0;
}
this.catCount[model.get('category_id')]++;
},
returnCount:function(){return this.catCount}
});
我初始化了这个集合几次

问题是,当我获取集合的
catCount
属性时,数组就像一个全局变量。因此,它不仅计算了集合自身实例中的模型,而且还计算了集合所有实例中添加的所有模型


有人知道如何使集合的属性只对其自己的实例计数吗?

也许您需要移动catCount来初始化函数

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

因此,它将在每个新集合实例中初始化

为什么要多次初始化此集合?。意思是多次绑定添加事件。我有需要分离的数据,但具有相同的结构(因此相同的模型和集合)。您可以通过创建模型或集合的多个实例来使用相同的结构。是的,这就是我正在做的:)