I am working on a small script implementing deferreds and ran across this little bit of code that isn’t behaving as I would expect Javascript to.
var dfd = $.Deferred()
, view = $.get("filename.tmpl");
$.get("filename.json")
.always(function (model) {
dfd.resolve(model);
});
$.when(view, dfd)
.done(function (view, model) {
// do stuff with view - even if there is no model
});
And this works fine, but when I refactor to this it stops working:
var dfd = $.Deferred()
, view = $.get("filename.tmpl");
$.get("filename.json").always(dfd.resolve);
$.when(view, dfd)
.done(function (view, model) {
// do stuff with view - even if there is no model
});
I don’t see any reason that this shouldn’t work. The function is expecting the first argument to be the model or undefined.
When you do this:
instead of this:
you will get a different object passed as the
thispointer for theresolve()method. The second will call it in the context ofdfd. The first will call it the context of the deferred object returned from your$.get()which is different.It important to remember that when passing a callback
dfd.resolvejust gets a pointer to the method. It does NOT set the context in whichresolvewill be called. That is set internally to the.always()method.