Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js sync event in collection

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?

like image 677
Karol Sikora Avatar asked May 25 '12 15:05

Karol Sikora


2 Answers

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');
}});
like image 136
Karol Sikora Avatar answered Oct 05 '22 02:10

Karol Sikora


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:

  1. Just listen to the add event and expect it be called repeatedly
  2. Emulate a single event by using a handler that has been debounced using the _.debounce() function.
  3. 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
    });
    
like image 30
Brian Reischl Avatar answered Oct 05 '22 01:10

Brian Reischl