-4

$(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?

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
Michael
  • 4,786
  • 11
  • 45
  • 68
  • 1
    "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." I don't know why I needed to paste that here, it's not hard to find: http://api.jquery.com/delegate/ – Jon Jun 14 '13 at 08:45
  • Just checking the DOC would have give you the answer... BTW, the delegate order of params is wrong here – A. Wolff Jun 14 '13 at 08:46

3 Answers3

0

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.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

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

http://api.jquery.com/on/

http://api.jquery.com/delegate/

steo
  • 4,586
  • 2
  • 33
  • 64
0

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005