Highway: wait for the continuation of multiple sampling

I take a collection of several pages, and I am looking for a way to find out when all the extracts are completed. This is what my collection looks like:

app.collections.Repos = Backbone.Collection.extend({ model: app.models.Repo, initialize: function(last_page){ this.url = ('https://api.github.com/users/' + app.current_user + '/watched'); for (var i = 1; i <= last_page; i++) { this.fetch({add: true, data: {page: i}}); }; }, ... 

Any idea how I could achieve this with clean code?

+7
source share
2 answers

Use jQuery deferreds :

 var deferreds = []; for (var i = 1; i <= last_page; i++) { deferreds.push(this.fetch({add: true, data: {page: i}})); }; $.when.apply($, deferreds).done(function() { ... <CODE HERE> ... } 

(I really haven't tested this, but I think it should work.)

JQuery documentation on when :

Provides a way to perform callback functions based on one or more objects, typically deferred objects representing asynchronous events.

And another answer that might help: How do you work with jQuery deferred arrays?

+13
source

One option is to use the underscore.js ' after function ( docs ), but this requires the use of -allback success, because there will be many additions:

 initialize: function(last_page){ this.url = ('https://api.github.com/users/' + app.current_user + '/watched'); var self = this; // save a reference to this var successCallback = _.after(function() { self.trigger('allPagesFetched'); //trigger event to notify all listeners that fetches are done }, last_page); // this function will be called when it has been called last_page times for (var i = 1; i <= last_page; i++) { this.fetch({add: true, data: {page: i}, success: successCallback}); }; }, 

Hope this helps!

+2
source

All Articles