Shorthand methods for unbind

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 .click() for .bind('click'), it should also include .unclick() for .unbind('click') for consistency. But he didn't consider two things:

  1. I can't change jQuery's API.
  2. 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 .unEvent() and .oneEvent() methods.

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:

[js](function($) { var eventTypes = ['blur','focus','resize','scroll','click','dblclick', 'mousedown','mouseup','mousemove','mouseover', 'mouseout','mouseenter','mouseleave','change','select', 'submit','keydown','keypress','keyup','error']; $.each(eventTypes, function(index, eventType) { jQuery.fn[ 'un' + eventType ] = function( fn ) { return this.unbind( eventType, fn ) ; }; }); })(jQuery); [/js]

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.

Update

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.



Responsive Menu
Add more content here...