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:
jQuery.extend({
scope: function(fn, scope)
{
return function()
{
return fn.apply(scope, arguments);
}
}
});
Which allows us to do the following...
myClass.prototype.addHandler = function(element)
{
$(element).click($.scope(this.handleClick, this));
}

myClass.prototype.handleClick = function()
{
// this refers to the myClass object, yay!
this.doStuff();
}
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).

For now, problem solved.

Comments

  1. Following your blog now, because if you keep posting this handy info, I might actually learn something beyond the basic usage of jQuery.

    ReplyDelete

Post a Comment

Popular posts from this blog

Complaint Sent to BBC Regarding F1 Coverage

Demystifying MONTAGE and MODX - new comprehensive tutorial series

Gotta Love Joined-Up Government