Backbone.js sync event in collection

According to the doc: http://documentcloud.github.com/backbone/#FAQ-events the collection has a synchronization event when I do something to synchronize with the server. I am trying to call the fetch method in a collection and wait for a synchronization event on it, but it will never happen. An event has been added, but I only need one event after synchronizing all the elements of the collection to update the corresponding view. Is there another way to trigger this event?

+6
source share
2 answers

The solution is to fire the synchronization event monumentally in the 'success' callback passed as the param method to retrieve.

this.collection.fetch({add: true, success: function(collection, response){ collection.trigger('sync'); }}); 
+5
source

I believe that the sync event is fired only when the model changes. Therefore, if you create, update, or delete a model, the "sync" event will occur.

In your case, I think you want to listen to the "reset" event in the collection.

Edit: If you set the {add:true} parameter, then there is no single Master event that will fire after all models have been added. You have several options:

  • Just listen to the add event and expect it to be called again
  • Emulating a single event using a handler that was debugged using the _.debounce() function.
  • The return value from fetch() is a jQuery XMLHttpRequest object. It implements the deferred jQuery interface . So you could listen to this finish. For instance:

     myCollection.fetch({add:true}).done(function(){ myView.render(); //or whatever }); 
+2
source

Source: https://habr.com/ru/post/916682/


All Articles