Someone sent me an email the other day, asking that I add shorthand methods for
.unbind(eventType) to the jQuery core file. He argued that since jQuery provides shorthands such as
.bind('click'), it should also include
.unbind('click') for consistency. But he didn't consider two things:
- I can't change jQuery's API.
- Those shorthand methods used to be part of jQuery core, but with the release of 1.0, John Resig cleaned up the API quite a bit, removing all of the
While I understand the desire for simplicity in developers' code and consistency in jQuery's API, I think Mr. Resig made the right decision removing the shorthand methods. Keeping both "un" and "one" shorthands in there would have meant an additional 44 methods, with very little gain for most users of the library. Nevertheless, it's fairly trivial to create a plugin for this sort of thing.
If we want the shorthand methods for a particular project, we can simply iterate through an array of event types and add the "un" or "one" method to the jQuery prototype (
jQuery.fn). Here is what it might look like:
To add the "one" shorthand methods, we can repeat lines 8– 9, using
one in place of both
un in line 8 and
unbind in line 9.
My apologies to everyone who saw this article as it was originally written. I messed things up when I replaced jQuery's
$.each() method with a native
for loop and failed to test the revision. I've modified it once more, putting the
$.each() method back in there. If you look at the jQuery core file where it creates
.click() and friends, you'll see where I got the idea.
Many thanks to Collin, Ralf, and especially Matthew, who were very kind to post comments pointing out the problems with the original script. I put all three versions — the original, the modified one above, and Matthew's version — in a single file for your downloading pleasure.