JQuery: unbinding with anonymous functions
In the last post of the JQuery series, we’ve seen how to “cancel” the subscription of an event fired by an HTML DOM node. At the time, I said that when you want to cancel a specific handler, you needed to create a function and pass a reference to it when you can the unbind method. I even said that you needed to create a named function and that you couldn’t use anonymous functions.
After publishing the post, I started thinking about that and then I remembered about the arguments.callee property. If you’re not familiar with it, then don’t worry because it’s really simple. From within a function, you can access the arguments object. This object works like an array that allows the argument values passed to the function to be retrieved by position instead of by name. Besides letting you access the passed in parameters, it also exposes two interesting properties: callee and caller. callee returns a reference to the current function object that is being executed. On the other hand, caller returns a reference to the arguments object of the calling function.
The callee property is what we’re interested in. Take a look at the following snippet:
$("#bt").bind("click", function() {
var fn = arguments.callee;
alert("hi");
$("#bt").unbind("click", fn); })
.bind("click", function() { alert("hi2"); });
If you run the previous snippet (assuming you’ve got, for instance, a button #bt), they you’ll see that the hi alert will only be show once. That happens because the anonymous function which shows that message is simply a one time event handler (more about this in future posts). As you can see, we start by getting a reference to the function through the arguments.callee property. After getting that reference, we only need to pass it to the unbind method in order to cancel the current event binding. Notice that since we’re passing a reference to the function, we’re not cancelling any other events.
And that’s all for now. Keep tuned for more on JQuery.