Recently the jQuery team start recommending to use on
instead of bind
for binding events to the DOM.
I would like to know if there is a difference between them, what is the benefit of using the on
function and if it would be a good call of changing all my bind
's to on
's functions in my code?
The jQuery project is moving towards putting more and more functionality in fewer methods, instead of having separate methods for every separate thing.
The methods bind
, live
and delegate
have all been replaced by the single method on
, where you use parameters of different types to determine what the method does.
Comparison:
$(sel).bind(event, f); = $(sel).on(event, f);
$(sel).live(event, f); = $(document.body).on(event, sel, f);
$(sel).delegate(sel2, event, f) = $(sel).on(event, sel2, f);
If you are using live
, you should replace that, as the usage of that method is a bit awkward. Also, the live
method creates a delegate on the body element, and you should try to bind the delegate to a closer scope.
If you are using bind
and delegate
it's no panic to replace them with on
right away. You can do that in new code, and in code that you edit anyway, but those methods are not about to go away in the nearest future.
basically there is no difference in basic use case
$( '#elementID' ).bind( 'click', function(){...} );
$( '#elementID' ).on( 'click', function(){...} );
these two are functionally same..
.on()
also does event delegation, and is thus preferred.
The idea for adding .on() was to create a unified event API, rather than having multiple functions for binding event;
.on() replaces .bind(), .live() and .delegate().
and as of jquery 1.7 ...bind
is just an alias of .on()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With