Understanding $.proxy on jQuery 1.4

Saturday, 23 January 2010

Posted by Sébastien Lachance with Comments (0)

One of my great resolution of the year is to learn by teaching. Today I watched the Day 9 videos of the 14 days of jQuery. In one of them, Paul Irish talked about $.proxy() and I did not totally understood what was going on.

The jQuery API definition is : Takes a function and returns a new one that will always have a particular scope. Well, I could read this all day long and I am sure It couldn’t be clearer without an example.

Here is the problem the “proxy” function is trying to solve.

 var me = {
            name: "Sebastien",
            blogging: function () {alert(this.name + " is blogging") }
        };

$(function () {
    me.blogging(); //will display : Sebastien is blogging
    $('#clickMeButton').click(me.blogging); //will display : is blogging
});

 

As we can see, on line 7, the function is called inside me (now that I think of it, this instance name is not perfect). But when called as the button click handler, the this keyword is now representing the button. And as the name property is not set on the button, nothing is displayed. Easily provable with :

 

$('#clickMeButton')[0].name = "Button"; 
$('#clickMeButton').click(me.blogging); //will display :Button is blogging

 

This could be awkward if not the desired behaviour. Let’s see how the jQuery team resolved that problem.

$(function () {
	me.blogging(); //will display : Sebastien is blogging
	$('#clickMeButton').click($.proxy(me, "blogging")); //will display :Sebastien is blogging
});

 

By calling the proxy method with the instance and the desired function, the context is now set to that instance. Resolving that particular problem. The method takes the instance and the name of the function as a string or could also be called by using :

$('#clickMeButton').click($.proxy(me.blogging, me));

I hope It helped you understand $.proxy(). I can already see where I can apply this knowledge right now.

 

 

Technorati Tags: ,



blog comments powered by Disqus