According to doc here: http://documentcloud.github.com/backbone/#FAQ-events collection has sync event fired when I do something to sync collection with server. I try to invoke fetch method on collection and wait for sync event on it, but it never happens. Add event is fired, but I need only one event after syncing all items in collection to update corresponding view. There is another way to get this event fired?
Asked
Active
Viewed 1.4k times
6
2 Answers
5
The solution is to fire up sync event maunually in 'success' callback passed as param to fetch method.
this.collection.fetch({add: true, success: function(collection, response){
collection.trigger('sync');
}});

Karol Sikora
- 522
- 1
- 4
- 11
-
1As of backbone 0.9.9 adding sync trigger on success callback is no longer needed. From http://backbonejs.org/#changelog Consolidated "sync" and "error" events within Backbone.sync. They are now triggered regardless of the existence of success or error callbacks. – Thaddeus Albers Dec 14 '13 at 00:38
2
I believe the "sync" event is only fired when you change a model. So if you create, update or delete a model, then the "sync" event will fire.
In your case, I think you want to listen for the "reset" event on the collection.
Edit:
If you're setting the {add:true}
option, then there is no single Backbone event that will fire after all the models have been added. You have a few options:
- Just listen to the
add
event and expect it be called repeatedly - Emulate a single event by using a handler that has been debounced using the
_.debounce()
function. The return value from
fetch()
is a jQuery XMLHttpRequest object. It implements the jQuery Deferred interface. So you could listen for that finish. For example:myCollection.fetch({add:true}).done(function(){ myView.render(); //or whatever });

Brian Reischl
- 7,216
- 2
- 35
- 46
-
Reset event does not suit my needs because I call fetch with add: true parameter. – Karol Sikora May 25 '12 at 15:26