Thursday, March 4, 2010

Quick Tip: Learning jQuery 1.4’s $.proxy

One of my favorite new features in jQuery 1.4 is the new $.proxy method. It allows us the ability to force a particular context when calling a method. In JavaScript, there can be times when it's difficult to hold on to the this keyword. For example, when it's bound to some event handler, this now refers to the target of the handler, rather than your desired object.

If this sounds a bit confusing, don't worry; today's four-minute video quick tip should clear things up.

// Create an object.
var obj = {
// this = obj
somevar : 'some value',

doSomething : function() {
alert(this.somevar);
}
};

// When bound to an event handler, this will
// refer to the target of the handler, or the div - not obj.
$('div').click(obj.doSomething); // undefined.

// With $.proxy, we pass two parameters.
// 1. The method to call.
// 2. The context.
// In this case, we're forcing obj to once again be equal to this.
$('div').click( $.proxy(obj.doSomething, obj) ); // some value


http://jsbin.com/inupo
http://net.tutsplus.com/videos/screencasts/quick-tip-learning-jquery-1-4s-proxy/

No comments: