Thursday 14 May 2015

Whats the difference $().click(fn) vs $().bind(‘click’,fn)


I was working on some event handling and I came across something that I was not quite sure of. What is the different between the 2 following pieces of code.

$('#abc').click(function(){
});

$('#abc').bind('click',function(){
});

I did some searching and came across this explanation on Stack Overflow. Basically the answer was look at the source, so I did. If you look at the source for jQuery you will see the following code.










jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) {

// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}

return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};

if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});

Basically for every one of those short hand event names, it is calling bind. So really there is no difference, so then I started asking myself, should I ever call the shorthand? I know there probably is not a huge difference but there has to be some performance benefit to using bind right? What do you guys think?