A common pattern in jQuery plugin development is the need to undo what the plugin has done. This is usually handled through a method prefixed with "un". Another common pattern is the use of anonymous functions for event handlers. Unbinding events is easy with jQuery but unbinding a single event handler requires the use of a named function. jQuery 1.2 now provides another option for binding and unbinding events: event namespaces.
As a very simple example, let's say I wrote a plugin called "clicked". It provides two methods:
clicked method attaches an event to all matched elements that when clicked adds a class name of "clicked" to the clicked element. The
unclicked method removes the "clicked" classes it might have set and the
clicked event handlers it attached. Here is the code:
You could use the plugin by calling it like this:
And if you wanted to stop using the plugin, you could just call
So far, so good.
But let's say I'm also using another plugin that attaches a click event to the same elements that the clicked plugin does. Calling
unclicked would unbind all the click events, including those bound by your own code or another plugin.
A Solution: Event Namespacing
Event namespacing provides a way to manage specific event handlers. For example, a plugin could namespace its event handlers to make them easier to unbind while still using anonymous functions. To namespace an event, just suffix the event type with a period and a name ("
Here is the clicked plugin again, but this time using event namespaces:
Now it only unbinds the events that it bound in the first place, leaving any other bound events alone.