Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with:

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

By Ben Nadel on

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

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?

@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 :)