Event scoping with jQuery in OOP: Controlling the value of ‘this’

One of the things I have always liked about jQuery since I first started using it is how easy it is to bind events to elements, and have easy access to the bound elements via “this”. However, when you start programming object oriented JavaScript, you lose access to the object’s “this” unless you use closure:

var self = this;
  if (self.editing) {
    // do something special

Other frameworks such as ExtJS and Mootools allow you to specify the scope of an event handler. JQuery does not. I thought that was a drawback until I figured out that they allow for it in a way that gives the best of both worlds:

$('#special_link').bind('click', {self:this}, this.onClick}
onClick: function(e){
  var self = e.data.self;
  // this = the element that was clicked

This way you have both the element that was clicked and the object whose scope you wanted. On the other hand, it means you’ll have to be mindful of what “this” and “self” refer to throughout your code.

That’s a price I can pay for now…

December 30, 2009 in JavaScript