Simple $.proxy onclick example

by hellosze

HTML

<div>Hello DIV</div>

JavaScript

// 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