2012-08-23 19 views
7

Recojo la colección de varias páginas y estoy buscando una forma de saber cuándo se completan todas las funciones. Esto es lo que mi colección es así:Backbone: Espere a que la búsqueda múltiple continúe

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

alguna idea de cómo podría lograr esto con un código limpio?

Respuesta

13

Uso 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> 
    ... 
} 

(. Yo en realidad no han probado esto, pero creo que debería funcionar)

documentación de jQuery en when:

proporciona una manera de ejecutar funciones de devolución de llamada basadas en uno o más objetos, generalmente objetos diferidos que representan eventos asíncronos.

Y otra respuesta que podrían ayudar: How do you work with an array of jQuery Deferreds?

2

Una opción es utilizar underscore.js 'after -función (docs), pero que requiere el uso de un éxito -callback, ya que habrá un montón de add - eventos:

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 help!

Cuestiones relacionadas