Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone JS Promises resolve before properties are set on model

Using a backbone model, assuming it fetches some additional properties from the server (like "FirstName" and "LastName"), I have something like the following:

var myModel = new Backbone.Model({ id: 10 });
var myOtherModel = new Backbone.Model({ id: 20 });
$.when(myModel.fetch(), myOtherModel.fetch()).done(function () {
    console.log(myModel.toJSON());
});

The output:

{ id: 10 }

The output a moment later:

{ id: 10, FirstName: "Joe", LastName: "Schmo" }

It would seem that Backbone's promises are flawed in that the jqXHR object returned has a promise that's resolved prior to backbone completing its own process.

Is this the case? Is there something else that must be done to ensure that the promise returned by fetch() isn't resolved until all of Backbone's sets are done, or at least the sets happen before my attached handler?

like image 813
Adam Terlson Avatar asked Aug 21 '12 14:08

Adam Terlson


1 Answers

Found the issue.

My model that I was fetching overrode Backbone.Model.sync.

    sync: function (method, model, options) {
                    // Some stuff
        Backbone.sync(method, model, options); // missing return
    }

Because it didn't return Backbone.sync() the promise was resolving immediately. I would have caught this if not for the $.when() wrapping the fetch() calls, which silently will accept any old thing, even if it's not a promise, and simply treat it as resolved immediately.

like image 55
Adam Terlson Avatar answered Oct 01 '22 17:10

Adam Terlson