Originally found on the Learning jQuery blog by Karl Swedberg
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:
- 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
.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:
-
(function($) {
-
var eventTypes = ['blur','focus','resize','scroll','click','dblclick',
-
'mousedown','mouseup','mousemove','mouseover',
-
'mouseout','mouseenter','mouseleave','change','select',
-
'submit','keydown','keypress','keyup','error'];
-
-
jQuery.fn[ 'un' + eventType ] = function( fn ) {
-
};
-
});
-
})(jQuery);
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.