2012-08-23 78 views
7

我獲取多個頁面的集合,並且正在尋找一種方法來知道何時完成所有提取。 下面是我收集的樣子:主幹:等待多次獲取繼續

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

任何想法,我能怎麼用乾淨的代碼實現這一目標?

回答

13

使用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> 
    ... 
} 

(我沒有實際測試過這一點,但我認爲它應該工作)

when

jQuery的文檔:

提供一種方法來基於一個或多個對象執行回調函數,通常表示異步事件的Deferred對象。

而另一個答案,這可能有助於:How do you work with an array of jQuery Deferreds?

2

一種選擇是使用underscore.jsafter - 功能(docs),但必要使用成功-callback,因爲會有附加了很多 - 事件:

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

希望這有助於!