$(document).on('click', '#target')
VS. $('body').delegate('click', '#target');
As I can see, both the above do the job I want, but I would like to know what is the best practice in this matter.
Is one more efficient than another?
$(document).on('click', '#target')
VS. $('body').delegate('click', '#target');
As I can see, both the above do the job I want, but I would like to know what is the best practice in this matter.
Is one more efficient than another?
delegate()
was superseded by on()
with jQuery 1.7. As the documentation states:
As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method.
No , simply in the latest version's of jQuery (if I'm not wrong 1.8+) .on
method suppress .delegate
method . So , if you use 1.8-
jQuery versione you have to use .delegate()
to accomplish several goal, on 1.8+ you need only .on()
method
There may be a slight performance difference, because clearly one will just call the other. The library doens't contain two separate implementations that does the same thing. That difference isn't relevant though, as another call is so little work compared to the rest of the work it does, and the actual implementation may change from one version to the other.
In contrast, the live
method isn't recommended to use, because its use is unintuitive, and because delegate
(or on
) allows you to limit the scope of the delegation. The delegate
method doesn't have such drawbacks compared to using on
for the same thing.
The author of the library goes in the direction of including more functions in fewer methods, so the recommendation from the author would be to use on
for everything. You don't have to follow that recommendation though, if you feel that using delegate
more clearly shows the intention of the code.