Workaround for jQuery's lack of scope management in event / AJAX handlers
Yesterday, I wrote about the importance of the ability to have event callback functions reference this as the containing object of the method in which the event listener was created, and noted that with version 1.3.2, jQuery does not support this functionality.
I also found that the latest version of jQuery (straight from SVN) supports scope assignment through the .bind() function. This seemed great, until I realised that it's necessary to have similar functionality for AJAX handlers too, and jQuery still lacks this.
Therefore, after some fiddling around, the following workaround was devised:
For now, problem solved.
I also found that the latest version of jQuery (straight from SVN) supports scope assignment through the .bind() function. This seemed great, until I realised that it's necessary to have similar functionality for AJAX handlers too, and jQuery still lacks this.
Therefore, after some fiddling around, the following workaround was devised:
jQuery.extend({Which allows us to do the following...
scope: function(fn, scope)
{
return function()
{
return fn.apply(scope, arguments);
}
}
});
myClass.prototype.addHandler = function(element)The very nice thing about this is that it can be used anywhere that jQuery offers a callback, simply by wrapping the callback function in $.scope(callback, this).
{
$(element).click($.scope(this.handleClick, this));
}
myClass.prototype.handleClick = function()
{
// this refers to the myClass object, yay!
this.doStuff();
}
For now, problem solved.
Following your blog now, because if you keep posting this handy info, I might actually learn something beyond the basic usage of jQuery.
ReplyDelete