Brent
Brent

Reputation: 2485

Jquery Promise Backbone Fetch

What I want to achieve is the PopUpView only gets called-once all the Models have been saved.

When running the code, the popup view runs before the saves have completed.

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

Upvotes: 1

Views: 69

Answers (2)

nikoshr
nikoshr

Reputation: 33344

  1. You can take advantage of the deferred return by model.fetch and model.save
  2. And you can mutate your promise by having then return a new promise1

You could build your array of promises like this

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

And a demo http://jsfiddle.net/nikoshr/du44m1ha/

1 Since jQuery 1.8

Upvotes: 1

Magus
Magus

Reputation: 15104

The problem is that fetch is asynchronous too. So when you hit the line $.when.apply(..., promises is an empty array. So the promise returned by when trigger the then directly.

Upvotes: 1

Related Questions