简体   繁体   中英

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?

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');
}});

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 }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM