Safer event handling with jQuery namespaced events
You’ve heard it many times before: make sure your JavaScript plays nice with other code, especially if you package it up as a plugin and share with other developers. Perhaps the most obvious thing to think about is global variables, which you want to avoid creating since they can easily clash with other global variables.
How you apply and remove event handlers may also cause problems that can be really hard to troubleshoot. Recently I was working on a project where I had attached a function to the window.resize
event. But my function simply would not run, and it took me forever to figure out why.
The culprit turned out to be a jQuery plugin that also attached a function to window.resize
when it was triggered (in this case to display a dialog). Problem is that when the dialog was dismissed, the script removed all window.resize
handlers like this:
$(window).unbind('resize');
Oops! That removed my function as well! Bad behaviour!
Fortunately jQuery provides an easy way to avoid this: Namespaced Events. When binding a function to an event, simply add a namespace:
$(window).bind('resize.myFabulousPlugin', function () {
// Do something useful
});
Now if you need to unbind the function from the event, you can do it safely without affecting other scripts that use the same event:
$(window).unbind('resize.myFabulousPlugin');
Much better.
Update: A note about the use of .bind()
and .unbind()
in these examples. If you’re using jQuery 1.7 or later you can also attach and remove event handlers with .on()
and .off()
. If you need your code to be backwards compatible, which is often the case, keep using .bind()
and .unbind()
.
- Previous post: CSS generated content and screen readers
- Next post: Hiding visible content from screen readers with aria-hidden