I’m a lover of MooTools, and get used to bind the callback functions, for example:
element.addEvent('click', callback.bind(this));
Assume this is the current execution context. This statement means that, I’m binding the execution context of this to the function callback. Also, as far as I know, certain browsers (e.g., Chrome) have added bind() into their JavaScript engines.
Now my job needs me to switch to using jQuery. Clearly, the bind() has a different meaning in jQuery, which is close to addEvent() in MooTools. I could not figure out a way to change the execution context. I had to do the following:
var that = this;
element.click(function () {
callback.apply(that); // Have to invoke it, and also with extra function wrapper
});
But I wanted to do something like:
element.click(callback.*bind*(this));
Any jQuery guru has ideas?
See jQuery.proxy().
element.click($.proxy(callback, this));