user2091464
user2091464

Reputation: 13

backbone custom properties for collection

So I'm trying count my models in my collection by the category they have.

This is my code:

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

I initialize this collection a couple of times.

The problem is that when I get the catCount property of the collection, the array acts like a global variable. So it didn't only count the models from its own instance of the collection, but the array is counting all the models that are added over all the instances of the collection.

Anyone know how to make a property of a collection only count towards its own instance?

Upvotes: 0

Views: 334

Answers (1)

Elephant
Elephant

Reputation: 1344

Maybe you need to move catCount to initialize function?

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

so it will be initialized every new collection instance

Upvotes: 1

Related Questions