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 »
49 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 »
11,238 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 »
49 Comments

@Ben,

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


Aug 31, 2010 at 3:05 PM // reply »
11,238 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
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
May 14, 2013 at 6:57 PM
The UX Of Prototyping: Low-Fidelity Is The New High-Fidelity
@Phillip, I'm not sure I follow what you mean? Are you saying that you looked at the list of widgets provided by the jQuery UI and let that be your style guide? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools