Reputation: 110972
I've a collection witch can paginate over a collection in the backend, so onscroll I lot another batch of items. I know the count of items in on the server. I'm looking for a way to extend all my collections with a getCounter
method. The idea is to set the server counter initially and when ever a user add or remove items from the collection the counter updates. Whats will be the best approach for this?
I think the problem is that the add
event is also fired when I fetch new items from the server. Otherwise I could just bind to add
and remove
events.
Upvotes: 6
Views: 1006
Reputation: 35940
You need to control which additions and removals should count, and which not. Two options come to mind.
Silence all operations which should not count with the silent:true
option, and hook up your counter to the add
, remove
and reset
events. This will put some limitations to the general use of the collection, because you can't utilize their events in all cases.
Override the add
, remove
and reset
methods to accept an extra option, which tells you whether the counter should be updated or not. Something like:
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
option, when the added or removed item should be counted:
var SomeCollection = PaginatedCollection.extend({ });
var someCollection = new SomeCollection();
someCollection.add(model, { count: true });
someCollection.remove(model, { count: true });
(Code samples untested)
Upvotes: 5