Is There An Advantage To Using JQuery's $().on('mouseenter',function(){}) Over $().mouseenter(function(){})?
Solution 1:
Not really, it's just a little faster as the mouseenter
function calls on
(or trigger
if called without argument) as can be seen in the source 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 contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
As you can see, the same can be said for many events.
Personally, I prefer to use the mouseenter
(or click
, etc.) function when I don't need the special features of on
: one of the big advantages in my opinion in using jQuery is that it makes the code less verbose and more readable. And I don't think you should be corrected, ask the guys who corrects you why he does that.
Solution 2:
Normally, the specific events like .click
or $.post
are shortcuts. They act the same as using the .on
and $.ajax
functions but the latter normally have greater flexibility. EG .on
can bind to multiple event while .click
only subscribes to clicks. Same applies to the $.ajax
function, there are more options where as the shortcuts have certain defaults set.
Solution 3:
There's no practical difference between the two, the shorthand functions (.click()
, .mouseover()
, etc) call .on()
to actually bind the event handler anyway. The only "advantage" to using .on()
directly is that you don't have the additional overhead of a second function call; I suspect that's likely to be marginal enough that it's a very premature optimisation though.
Solution 4:
It's not neccessarily wrong, but on has its advantages over the normal way.
By "binding" the event to your parent container $(parent).on(event, target, function() { //foobar });
you are able to add new target elements into your container, while not having to repeat the jquery to bind the event.
Post a Comment for "Is There An Advantage To Using JQuery's $().on('mouseenter',function(){}) Over $().mouseenter(function(){})?"