Wednesday, 7 August 2013

Collection create function firing add event too quickly

Collection create function firing add event too quickly

I have a list view of sorts where the user can click a button to show a
modal view. The list view has a counter that shows the amount of items
contained in the list. Clicking a button in the modal view executes create
on a collection that is passed into both views. This fires the add event
in the list view, which in turn runs this function:
renderCount: function () {
// Container for model count
var $num = this.$el.find('.num');
if ($num.length > 0) {
// 'count' is a value returned from a service that
// always contains the total amount of models in the
// collection. This is necessary as I use a form of
// pagination. It's essentially the same as
// this.collection.length had it returned all models
// at once.
$num.html(this.collection.count);
}
}
However, add seems to be fired immediately (as it should be, according to
the docs), before the collection has a chance to update the model count. I
looked into sync but it didn't seem to do much of anything.
How can I make sure the collection is updated before calling renderCount?
Here's the initialize function, for reference:
initialize: function(options) {
this.businessAccounts = options.businessAccounts;
this.listenTo(this.businessAccounts, 'add remove reset',
this.renderCount);
this.render();
}

No comments:

Post a Comment