Be Careful When Using The jQuery Proxy() Method Outside Of A jQuery Context
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.
Want to use code from this post? Check out the license.
Reader Comments
Oh man, good to know.
@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.
thanks for this info