I’m building a Backbone application and I’m observing some behaviour I can’t place. Consider the following Collection:
window.Pictures = Backbone.Collection.extend({
model: Picture,
url: 'latest.json',
parse: function(response) {
this.foobar = 1;
},
fetchPage: function() {
this.foobar = 2;
return this;
}
});
On a Chrome (or Firefox) console I’ve issued the following command:
> p = new Pictures(); p.fetch(); p.fetchPage();
> p.foobar
1
When I do:
> p = new Pictures(); p.fetch()
> p.fetchPage();
> p.foobar
2
I really don’t understand this. Why is the first execution different from the second execution?
The
fetchcall is asynchronous because it involves an AJAX call to the server:And
fetchwill callparse:So
p.parse()may be called before or afterp.fetchPage()depending on timing issues that are beyond your control.In the first case:
fetchPageis getting called beforefetchgets its response from the server and gets around to callingparseso the calling sequence ends up like this this:p.fetch().p.fetchPage().p.parse().In the second case:
Enough time passes between the lines for the AJAX call to return before
p.fetchPage()is called so things happen in the order expect purely by accident.If you need things to happen in a certain order then you’ll need to use the
success(and possiblyerror) callback thatfetchprovides:So this should give you a consistent result of 2:
Of course, if
fetchPageinvolves an AJAX call then you’d have to add yet another layer of callbacks to get a consistentfoobarvalue.