kalisjoshua
kalisjoshua

Reputation: 2496

jQuery Deferred weirdness

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.

Upvotes: 2

Views: 98

Answers (1)

jfriend00
jfriend00

Reputation: 707218

When you do this:

$.get("filename.json").always(dfd.resolve);

instead of this:

$.get("filename.json")
  .always(function (model) {
    dfd.resolve(model);
});

you will get a different object passed as the this pointer for the resolve() method. The second will call it in the context of dfd. 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.resolve just gets a pointer to the method. It does NOT set the context in which resolve will be called. That is set internally to the .always() method.

Upvotes: 2

Related Questions