javascript – Backbone:等待多次获取继续

前端之家收集整理的这篇文章主要介绍了javascript – Backbone:等待多次获取继续前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
获取了多个页面的集合,我正在寻找一种方法来了解何时完成所有提取.
这是我的收藏品的样子:
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 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文档:

Provides a way to execute callback functions based on one or more objects,usually Deferred objects that represent asynchronous events.

另一个可能有帮助的答案:How do you work with an array of jQuery Deferreds?

原文链接:https://www.f2er.com/js/159453.html

猜你在找的JavaScript相关文章