jQuery’s .bind() vs. .on()
Internally, .bind
maps directly to .on
in the current version of jQuery. (The same goes for .live
.) So there is a tiny but practically insignificant performance hit if you use .bind
instead.
However, .bind
may be removed from future versions at any time. There is no reason to keep using .bind
and every reason to prefer .on
instead.
These snippets all perform exactly the same thing:
element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });
However, they are very different from these, which all perform the same thing:
element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });
The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.
jQuery's on()
function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).
The direct methods and .delegate
are superior APIs to .on
and there is no intention of deprecating them.
The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an
event name rather than a silent bug. In my opinion, it's also easier to write and read click
than on("click"
The .delegate
is superior to .on
because of the argument's order:
$(elem).delegate( ".selector", {
click: function() {
},
mousemove: function() {
},
mouseup: function() {
},
mousedown: function() {
}
});
You know right away it's delegated because, well, it says delegate. You also instantly see the selector.
With .on
it's not immediately clear if it's even delegated and you have to look at the end for the selector:
$(elem).on({
click: function() {
},
mousemove: function() {
},
mouseup: function() {
},
mousedown: function() {
}
}, "selector" );
Now, the naming of .bind
is really terrible and is at face value worse than .on
. But .delegate
cannot do non-delegated events and there
are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.