Using jQuery's Proxy() Method In Event Binding And Unbinding

Posted August 31, 2010 at 10:56 AM by Ben Nadel

Tags: Javascript / DHTML

Yesterday, I explored the use of jQuery's native event management in the creation of object-oriented publication and subscription (pub/sub) functionality. In order to do this, I had to make use of jQuery's new proxy() method that allows function callbacks to be executed in the context of an object instance rather than a DOM node (which is typically what happens). At its core, the proxy() method is basically an easy way to use Javascript's apply()-based context-binding. However, using proxy() instead of apply() allows jQuery to manage the relationship between functions which, ultimately, makes our programming lives much easier.

 
 
 
 
 
 
 
 
 
 

You'd have to look in the source code of the jQuery library to know this, but what makes proxy() so awesome is the fact that jQuery pulls the unique ID of the core method through to all of its proxies:

  • proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;

As you can see here, jQuery keeps an internal counter to represent a "guid" (Globally Unique ID). When a function goes through the proxy() method, jQuery generates a new guid value and then applies that guid to both the core function as well as the resultant proxy function. It does this so that you can use the original function reference to unbind an event handler callback that has been proxied - jQuery uses the guid to test for function equivalence during the unbind process.

To see this in action, I've created a small jQuery demo in which a function is bound to an event using the proxy method; then, later on, the same event handler is unbound using the original function reference.

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <title>jQuery Proxy() Method For Function Wrapping</title>
  • <script type="text/javascript" src="./jquery-1.4.2.js"></script>
  • <script type="text/javascript">
  •  
  • // Create a number of differnet girls to be used
  • // as execution contexts for an event handler (callback).
  • var joanna = {
  • name: "Joanna"
  • };
  •  
  • var sarah = {
  • name: "Sarah"
  • };
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Now, let's create a function that we'll use an event
  • // handler off of the document object. It will make reference
  • // to a "name" property which it will have to get from its
  • // execution context.
  • var handler = function( event ){
  • // Log name-based message.
  • console.log( "Hello, " + this.name );
  • };
  •  
  •  
  • // Bind the event handler and proxy the method several times.
  • // Notice that we are passing the resultant proxy method back
  • // to the proxy method several times.
  • $( document ).bind(
  • "test",
  • $.proxy(
  • $.proxy( handler, joanna ),
  • sarah
  • )
  • );
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Trigger the context-bound event handler.
  • $( document ).trigger( "test" );
  •  
  • // Now, unbind the event using the original event handler.
  • // Remember, when we bound to this event, we passed in a
  • // twice-proxied event handler.
  • $( document ).unbind( "test", handler );
  •  
  • // Try to trigger the event again to make sure that there
  • // are no lingering event handlers bound to the event.
  • $( document ).trigger( "test" );
  •  
  • // For debugging.
  • console.log( "Done" );
  •  
  • </script>
  • </head>
  • <body>
  • <!-- Intentionally left blank. -->
  • </body>
  • </html>

As you can see here, our original function reference, "handler," is being proxied twice before it actually gets passed into jQuery's bind() method. Then, when we go to unbind the event, we are using the original handler reference. When we run the above code, we get the following console output:

Hello, Joanna
Done

As you can see here, the second trigger() invocation did not result in any console output because there were no longer any event handlers bound to the given event type; passing the original handler reference to the unbind() method was successful.

There are two critical points to take away from this code: first, jQuery's proxy() method is the most awesome way to bind context-sensitive event handlers because we can always unbind the event handlers using the original function references. Second, once a function is proxied, attempting to proxy it again is useless. If you look at the code, you'll notice that the handler is first proxied to "joanna" and then, subsequently, to "sarah." Yet, when we trigger() the event, it is "Joanna" that we see in the console. Technically, the "sarah" proxy worked; however, the context-binding is encapsulated within the resultant proxy function. As such, the most-inner proxy will always execute in the context of the object to which it was originally bound.

When I first learned about jQuery's proxy() method, I thought it was a little silly; after all, Javascript already has call() and apply() methods for changing execution context. But, once you realize that jQuery's proxy() method allows you to easily bind() and unbind() event handlers regardless of context, it becomes obvious just how powerful this method is.

NOTE: The proxy() method can also take the following signature: jQuery.proxy( object, methodName ). This is functionally equivalent to jQuery.proxy( object[ methodName ], object ). While I use the latter in my demo, I would definitely use the former, more succinct proxy() signature in a true object-oriented setting.




Reader Comments

Aug 31, 2010 at 11:40 AM // reply »
48 Comments

OK... so your point on the second bind to sarah is that proxy does not form secondary binding. It will always point to the primary bind object?


Aug 31, 2010 at 2:20 PM // reply »
10,638 Comments

@John,

It forms the secondary binding; but, the functions execute form the outside-in. As such, the inner one will always win out, which was the original proxy. So, even though the outer one says "Execute function XYZ in *my* context", function "XYZ" actually points to a function that says, "execute function ABC in *my* context".

It's a bit confusing to visualize - I hope I didn't make it more confusing :)


Aug 31, 2010 at 3:02 PM // reply »
48 Comments

@Ben,

You did not thicken the fog... seems to be about the same visibility. LOL


Aug 31, 2010 at 3:05 PM // reply »
10,638 Comments

@John,

Ha ha ha :)


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 3, 2012 at 10:49 PM
How I Got Node.js Running On A Linux Micro Instance Using Amazon EC2
Wow this was really helpful! Only thing I would add is you need to update your .bash_profile after you edit the secure_path. This is what I did: $ . ~/.bash_profile Otherwise, NPM won't be found. ... read »
Feb 3, 2012 at 10:14 PM
Pushing Base64-Encoded Images Over HTML5 WebSockets With Pusher And ColdFusion
@Ben, Just wanted to let you know that pusher are soon to start limiting sizes on messages. This was the detail that came through in the Feb dispatch: "However, we will soon be limiting the s ... read »
Feb 3, 2012 at 5:05 PM
Regular Expressions Make CSV Parsing In ColdFusion So Much Easier (And Faster)
I tried using your RegEx in my C# program, but it was matching an extra empty-string at the end and so I would end up with an extra field that doesn't exist, so I changed it to this: (^|,)("(?: ... read »
Feb 3, 2012 at 3:47 PM
ColdFusion Supports HTTP Verbs PUT And DELETE (As Well As GET And POST)
Josh Cyr posted this on Twitter just a little bit ago. Thought it was appropriate. http://stackoverflow.com/questions/1619152/how-to-create-rest-urls-without-verbs/1619677#1619677 ... read »
Feb 3, 2012 at 2:28 PM
Changing The Execution Context Of Your Self-Executing Function Blocks In JavaScript
@Michael, You definitely make a good point (and extra points for quoting movies - I love movies). When you use a return() statement to define the object's public API, it does provide a consistent a ... read »
Feb 3, 2012 at 2:04 PM
Changing The Execution Context Of Your Self-Executing Function Blocks In JavaScript
To quote Jurassic Park: "Just because you can doesn't mean you should". I completely, utterly disagree with the thought that this is more readable. Consider the current module pattern: if ... read »
Feb 3, 2012 at 1:10 PM
REST API Design Rulebook By Mark Masse
@Jordan, Yeah, WRML was created by Mark Masse (author of the book). I also found it to be a bit convoluted. I suppose it is intended to allow the Client to be able to programmaticaly respond to cha ... read »
Feb 3, 2012 at 1:08 PM
ColdFusion Supports HTTP Verbs PUT And DELETE (As Well As GET And POST)
@Jason, To be honest, I don't have good answers for that kinds of stuff. And, to the point, that is specifically why I *really* liked the REST API Design Rulebook by Mark Masse - he just cuts throu ... read »