Reputation: 6540
I have a function that need to wait for another function to be done before it can be called so I try to use jquery deferred
. So for example:
firstFunction().done(secondFunction)
But secondFunction
has in its scope some usages of this
keyword so when it is called via done
it don't have access for proper this
property. For more those functions are placed in different files. Is there a way to call secondFunction
with proper this
property?
Upvotes: 0
Views: 37
Reputation: 17878
Yes, you can bind the function to the correct context.
For IE9 and up you can use native Javascript for this, namely Function.prototype.bind
firstFunction().done(secondFunction.bind(this));
If for some reason you're supporting IE8 then you either need to polyfill it (there's a recipe for that on the mdn page linked above) or you can use underscore's bind which should be available since it's required by backbone.
firstFunction().done(_.bind(secondFunction, this));
Upvotes: 1