1

If I have a backbone collection that has a method that calls an asynchronous method on each of its models like this:


getStatus: function() {
  this.each(function(model) {
    model.getStatus();
  });
}

And in the model class, an asynchronous ajax call is made like this:


getStatus: function() {
  $.ajax({
    //ajax properties here
  });
}

How can I determine when each and every model has completed it's asynchronous call (not necessarily successfully) and returned?

So in my collection, I need a getStatusSuccess method that executes after all these asynchronous calls have been completed. I have looked into jQuery deferreds, and I have tried a few things to get it to work, but to no avail. However, I still believe that it can be solved using deferreds.

4

3 回答 3

2
  • $.ajax返回一个延迟对象
  • 你可以结合 Deferred 对象jQuery.when来产生一个“master” Deferred

    在将多个 Deferred 对象传递给 jQuery.when 的情况下,该方法从一个新的“主” Deferred 对象返回 Promise,该对象跟踪它已传递的所有 Deferred 的聚合状态。
    该方法将在所有 Deferred 解析后立即解析其主 Deferred,或者在其中一个 Deferred 被拒绝时拒绝主 Deferred。

  • Backbone 在集合上代理了许多来自 Underscore 的函数,特别是_.invoke它返回一个包含调用结果的数组

  • function.apply将允许您调用具有给定上下文和作为数组提供的参数的函数

结合所有这些:

var M = Backbone.Model.extend({
    getStatus: function() {
        return $.ajax({
            // ...
        });
    }
});
var C = Backbone.Collection.extend({
    model: M,
    getStatus: function() {
        var jqXHRs = this.invoke('getStatus');
        return $.when.apply(this, jqXHRs);
    }
});

var c = new C([
    {id: 1},
    {id: 2}
]);
c.getStatus().always(function() {
    console.log('done');
});

还有一个演示http://jsfiddle.net/nKDjW/

于 2013-08-22T01:23:22.760 回答
0

可以建议两种方式来推迟通话:

  1. jQuery$.when()构造,上面nikoshr完美描述
  2. 或 Underscore_.after(count, function)方法,它基本上采用两个参数:异步调用的数量和您对 defer 的调用。
于 2013-08-23T09:30:12.710 回答
0

查看我最近在 Node.js 中的操作序列中的答案。

基本上你可以使用Async.js。检查它的并行功能..

于 2013-08-21T21:28:14.707 回答