Jquery 承诺 Backbone 获取

Jquery Promise Backbone Fetch

我想要实现的是 PopUpView 只有在所有模型都被保存后才会被调用。

当 运行 代码时,弹出视图在保存完成之前运行。

var promises = []
_.each(exampleModels, _.bind(function (resource) {
    var filter = this.resources.get(resource.id);
    filter.fetch(
            {
                success: function (model, response) {
                    var participant = new Model({
                        example: "text"
                    });
                    promises.push(participant.save());
                }
            });
}, this));

$.when.apply($, promises).then(_.bind(function () {
    var popupForm = new PopUpView({

    });
    this.$el.append(popupForm.$el);
}, this));

问题是 fetch 也是异步的。因此,当您点击行 $.when.apply(... 时,promises 是一个空数组。所以 when 返回的承诺直接触发 then

  1. 您可以通过 model.fetchmodel.save
  2. 利用 deferred return
  3. 你可以通过 then return a new promise1
  4. 来改变你的承诺

您可以像这样构建您的承诺数组

var promises = _(ids).chain()
    .map(function(id) {
        // get the models you want 
        return c.get(id);
    })
    .map(function(model) { // build a promise for each model
        return model.fetch(). // promise returned by fetch
            then(function(resp) {
                var participant = new M({
                    example: "text"
                });
                return participant.save(); // promise returned by save
            });
    })
    .value();

$.when.apply($, promises).then(function() {
    console.log('done');
});

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

1 因为 jQuery 1.8