主干:等待多次提取继续

Backbone: Wait for multiple fetch to continue

本文关键字:提取 继续 等待 主干      更新时间:2023-09-26

我获取多个页面的集合,我正在寻找一种方法来知道何时完成所有获取。以下是我的收藏:

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

知道我如何用干净的代码实现这一点吗?

使用jQuery延迟:

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

(我还没有真正测试过,但我认为它应该有效。)

jQuery关于when:的文档

提供一种基于一个或多个对象执行回调函数的方法,这些对象通常是表示异步事件的Deferred对象。

另一个可能有帮助的答案是:如何处理jQuery Deferred数组?

一个选项是使用underscore.js'after-函数(docs),但这需要使用成功回调,因为会有很多添加事件:

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

希望这能有所帮助!