Be Careful When Using The jQuery Proxy() Method Outside Of A jQuery Context

Posted December 19, 2011 at 10:56 AM by Ben Nadel

Tags: Javascript / DHTML

Over the weekend, I spent a few hours trying to wrap my head around some modular JavaScript application development. In order to keep my modules decoupled from one another, I tried to make appropriate use of the publish / subscribe method of communication. One problem that I ran into, however, was that I was using jQuery's proxy() method to bind callbacks to contexts. This works great in a full jQuery context; but, when you try to use those callbacks outside of a jQuery context, things don't work quite as well as you would hope.


 
 
 

 
  
 
 
 

In a weird way, the problem with ever using jQuery's proxy() method is that it is too magical! You can proxy() a given function an infinite number of times; and, when you go to unbind it from the jQuery event system, it just works. jQuery does this by assigning an internal GUID (Globally Unique ID) value to each function that gets proxied. Then, when a function is tested for equivalence (as part of the unbind process), jQuery compares the GUID values rather than the actual function references. This allows both a function and its proxy to be seen as the "same" function within the jQuery event system.

The jQuery proxy() method is awesome. So awesome, in fact, that I completely forgot that it wouldn't work outside of a jQuery context. In the code that I was writing over the weekend, I was using a Signal module to create an event beacon for each event-type within my code. I was then using jQuery's proxy() method to subscribe objects to the event Signals. To see what I'm talking about, take a look at this simplified code which creates a Signal, binds to it, triggers it, and then tries to unbind from it:

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <title>Using jQuery Proxy() Outside of jQuery</title>
  •  
  • <!-- Load scripts. -->
  • <script type="text/javascript" src="../jquery-1.7.js"></script>
  • <script type="text/javascript">
  •  
  •  
  • // Define the signal class for simple publish / subscribe
  • // functionality.
  • var Signal = (function(){
  •  
  • // I return an initialized instance.
  • function Signal( context, eventType ){
  •  
  • // Store the instance variables.
  • this.context = context;
  • this.eventType = eventType;
  •  
  • // Store an array of callbacks for this signal.
  • this.callbacks = [];
  •  
  • }
  •  
  •  
  • // Define the class methods.
  • Signal.prototype = {
  •  
  • // I subscribe a callback to this event.
  • bind: function( callback ){
  •  
  • // Add the callback to our list of subscribers.
  • this.callbacks.push( callback );
  •  
  • },
  •  
  •  
  • // I publish the event to all subscribers.
  • trigger: function(){
  •  
  • // Create an argument collection for the callbacks.
  • var eventArguments = Array.prototype.slice.call(
  • arguments
  • );
  •  
  • // Create an event object.
  • var event = {
  • context: this.context,
  • eventType: this.eventType,
  • date: new Date()
  • };
  •  
  • // Add the event to the list of arguments.
  • eventArguments.unshift( event );
  •  
  • // Loop over all the callbacks to publish the
  • // event object.
  • for (var i = 0 ; i < this.callbacks.length ; i++){
  •  
  • // Publish event.
  • this.callbacks[ i ].apply(
  • this.context,
  • eventArguments
  • );
  •  
  • }
  •  
  • },
  •  
  •  
  • // I unsubscribe the given callback from the event.
  • unbind: function( callback ){
  •  
  • // Map the callback OUT of the subscribers list.
  • this.callbacks = $.map(
  • this.callbacks,
  • function( thisCallback ){
  •  
  • // Check to see if this is the callback
  • // that we are unsubscribing.
  • if (callback === thisCallback){
  •  
  • // Return NULL to remove from list.
  • return( null );
  •  
  • }
  •  
  • // If we made it this far, then we are not
  • // unsubscribing the given callback.
  • return( thisCallback );
  •  
  • }
  • );
  •  
  • }
  •  
  • };
  •  
  •  
  • // Return the constructor.
  • return( Signal );
  •  
  • })();
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Create a random signal.
  • var someEvent = new Signal( window, "someEvent" );
  •  
  •  
  • // Create some object that has a callback.
  • var someObject = {
  •  
  • callback: function( event, message ){
  •  
  • // Log the event.
  • console.log( "SomeEvent happened!", message );
  •  
  • }
  •  
  • };
  •  
  •  
  • // Subscribe the object to the event. When doing this, we are
  • // going to use the jQuery proxy object to bind the free-
  • // floating method to the object on which it should be called.
  • someEvent.bind(
  • $.proxy( someObject.callback, someObject )
  • );
  •  
  •  
  • // Trigger the signal.
  • someEvent.trigger( "Woohoo!" );
  •  
  •  
  • // Unbind the object callback.
  • someEvent.unbind( someObject.callback );
  •  
  •  
  • // Trigger the event again to see if the callback was truly
  • // unbound.
  • someEvent.trigger( "Woohoo 2!" );
  •  
  •  
  • </script>
  • </head>
  • <body>
  • <!-- Left intentionally blank. -->
  • </body>
  • </html>

As you can see, I am using the jQuery proxy() method as a way to bind the subscriber callback to a given context:

  • someEvent.bind(
  • $.proxy( someObject.callback, someObject )
  • );

If this were a pure jQuery event system, this would be absolutely fine; the internal GUID (Globally Unique ID) value would be used to determine equivalence. But, since the Signal module is not part of the jQuery library, the subsequent unbind() call fails to work. And, when we run the above code, we get the following console output:

SomeEvent happened! Woohoo!
SomeEvent happened! Woohoo 2!

As you can see, the callback was never unsubscribed from the event; and, a subsequent triggering of the event precipitated a second callback invocation.

The problem with the Signal module is that it only compares callback references. Since the original callback and its proxied version are two separate function instances, the original version cannot be used to unsubscribe the proxied callback reference.

We could fix this problem by building the jQuery GUID logic into our Signal class' unbind() method:

  • // Check to see if this is the callback
  • // that we are unsubscribing.
  • if (
  • (callback === thisCallback)
  • ||
  • (
  • callback.hasOwnProperty( "guid" ) &&
  • thisCallback.hasOwnProperty( "guid" ) &&
  • (callback.guid === thisCallback.guid)
  • )
  • ){
  •  
  • // Return NULL to remove from list.
  • return( null );
  •  
  • }

The problem with this is that the Signal module now becomes highly coupled to the jQuery library. This solves the problem by introducing a potentially worse problem.

The better solution is simply to remove the use of the jQuery proxy() method and to build its functionality into the Signal module. Rather than passing a lone callback to the bind() method, let's update the code to use a callback and a context (on which the callback will eventually be invoked):

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <title>Using jQuery Proxy() Outside of jQuery</title>
  •  
  • <!-- Load scripts. -->
  • <script type="text/javascript" src="../jquery-1.7.js"></script>
  • <script type="text/javascript">
  •  
  •  
  • // Define the signal class for simple publish / subscribe
  • // functionality.
  • var Signal = (function(){
  •  
  • // I return an initialized instance.
  • function Signal( context, eventType ){
  •  
  • // Store the instance variables.
  • this.context = context;
  • this.eventType = eventType;
  •  
  • // Store an array of subscribers for this signal.
  • this.subscribers = [];
  •  
  • }
  •  
  •  
  • // Define the class methods.
  • Signal.prototype = {
  •  
  • // I subscribe a callback to this event.
  • bind: function( callback, context ){
  •  
  • // Default the context.
  • context = (context || window);
  •  
  • // Add the callback to our list of subscribers.
  • // Store the context with the subscriber so we
  • // can set the context when publishing.
  • this.subscribers.push({
  • callback: callback,
  • context: context
  • });
  •  
  • },
  •  
  •  
  • // I publish the event to all subscribers.
  • trigger: function(){
  •  
  • // Create an argument collection for the callbacks.
  • var eventArguments = Array.prototype.slice.call(
  • arguments
  • );
  •  
  • // Create an event object.
  • var event = {
  • context: this.context,
  • eventType: this.eventType,
  • date: new Date()
  • };
  •  
  • // Add the event to the list of arguments.
  • eventArguments.unshift( event );
  •  
  • // Loop over all the subscribers to publish the
  • // event object to their callbacks.
  • for (var i = 0 ; i < this.subscribers.length ; i++){
  •  
  • // Publish event.
  • this.subscribers[ i ].callback.apply(
  • this.subscribers[ i ].context,
  • eventArguments
  • );
  •  
  • }
  •  
  • },
  •  
  •  
  • // I unsubscribe the given subscriber from the event.
  • unbind: function( callback ){
  •  
  • // Map the callback OUT of the subscribers list.
  • this.subscribers = $.map(
  • this.subscribers,
  • function( subscriber ){
  •  
  • // Check to see if this is the callback
  • // that we are unsubscribing.
  • if (callback === subscriber.callback){
  •  
  • // Return NULL to remove from list.
  • return( null );
  •  
  • }
  •  
  • // If we made it this far, then we are not
  • // unsubscribing the given callback.
  • return( subscriber );
  •  
  • }
  • );
  •  
  • }
  •  
  • };
  •  
  •  
  • // Return the constructor.
  • return( Signal );
  •  
  • })();
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Create a random signal.
  • var someEvent = new Signal( window, "someEvent" );
  •  
  •  
  • // Create some object that has a callback.
  • var someObject = {
  •  
  • callback: function( event, message ){
  •  
  • // Log the event.
  • console.log( "SomeEvent happened!", message );
  •  
  • }
  •  
  • };
  •  
  •  
  • // Subscribe the object to the event.
  • //
  • // NOTE: This time, when subscribing the callback, we are
  • // using the bind() method to encapsulate the binding of
  • // the callback to the subscriber context.
  • someEvent.bind( someObject.callback, someObject );
  •  
  •  
  • // Trigger the signal.
  • someEvent.trigger( "Woohoo!" );
  •  
  •  
  • // Unbind the object callback.
  • someEvent.unbind( someObject.callback );
  •  
  •  
  • // Trigger the event again to see if the callback was truly
  • // unbound.
  • someEvent.trigger( "Woohoo 2!" );
  •  
  •  
  • </script>
  • </head>
  • <body>
  • <!-- Left intentionally blank. -->
  • </body>
  • </html>

Notice that this time, our Signal module doesn't have a list of callbacks; rather, it has a list of subscribers. And, each subscriber has a callback and a context associated with it. Now, when the Signal module goes to publish an event to the callbacks, it can explicitly do so on the given context objects. This time, when we run the above code, we get the following console output:

SomeEvent happened! Woohoo!

As you can see, the subscribed callback was only invoked once; this indicates that the unbind() method successfully unsubscribed the given callback from the event type.

As an aside, I just wanted to mention that you could also solve this problem by defining object methods as closures on said objects. Doing so allows a method reference to be passed around without an explicit context. The jQuery library does this with its Deferred objects specifically so that the Deferred methods can be passed around with ease.

Outside of narrowly focused utilities like Deferred objects, however, I am very hesitant to ever define the methods of an instantiatable object as closures of that object. Doing so negates all of the benefits of prototype-based inheritance, and, in my mind, is only replacing one problem with another.

The jQuery proxy() method is awesome. It makes binding and unbinding event handlers incredibly easy - when you're in a jQuery context. When you're not in a jQuery context, the jQuery proxy() method completely stops working; or rather, it makes you realize how unaware you are of just how magical it is.




Reader Comments

Dec 19, 2011 at 2:49 PM // reply »
1 Comments

Oh man, good to know.


Dec 19, 2011 at 3:32 PM // reply »
11,238 Comments

@Ed,

Took me a few minutes to debug. But mostly, I'm glad I got bitten by this so that it forced me to think more deeply about how it works and when / why it should be used.


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