Assembly counter

I have a collection that can be divided into several pages per backend, so onscroll I have another batch of items. I know the number of items on the server. I am looking for a way to expand all my collections with the getCounter method. The idea is to set the server counter first, and when the user adds or removes items from the collection, updates the counter. What would be the best approach for this?

I think the problem is that the add event is also triggered when I retrieve new items from the server. Otherwise, I could just snap to the add and remove events.

+6
source share
1 answer

You need to control which supplements and removals should be considered and which should not. Two options come to mind.

  • Disable all operations that should not be taken into account using the silent:true parameter, and connect the counter to the add , remove and reset events . This will impose some restrictions on the general use of the collection, because you cannot use their events in all cases.

  • Override add , remove and reset methods to accept an additional option that tells you whether to update the counter or not. Sort of:

     var PaginatedCollection = Backbone.Collection.extend({ initialize: function() { this._counter = 0; }, add: function(models, options) { if(options && options.count) this._counter += (_.isArray(models) ? models.length : 1); Backbone.Collection.prototype.add.apply(this, arguments); }, remove: function(models, options) { if(options && options.count) this._counter -= (_.isArray(models) ? models.length : 1); Backbone.Collection.prototype.remove.apply(this, arguments); }, reset: function(models, options) { if(options && options.count) this._counter = (_.isArray(models) ? models.length : 0); Backbone.Collection.prototype.reset.apply(this, arguments) } }); 

    And pass the count:true parameter when you need to add the added or deleted item:

     var SomeCollection = PaginatedCollection.extend({ }); var someCollection = new SomeCollection(); someCollection.add(model, { count: true }); someCollection.remove(model, { count: true }); 

(code samples not verified)

+5
source

All Articles