user920041
user920041

Reputation:

In jQuery, should I choose live(), delegate() or on()?

I've read the jQuery documentation on event handling, but I still can't really understand what I should do.

I have a mobile app where content is loaded with ajax, so events can't be bound at document onLoad for that content.

As my application grow I now start to be concerned that wrong event handling can give performance problem.

What is the implications on performance choosing between on(), live() and delegate() ?

Something else to take into consideration?

Upvotes: 6

Views: 183

Answers (4)

Alex Peattie
Alex Peattie

Reputation: 27647

From jQuery 1.7, the official (and most performant) way to bind events is .on and .off. It's fastest when combined with an id based selector:

$('#id').on('click', myHandler);

.on supercedes .live .delegate and .bind, see here for more info:

http://blog.jquery.com/2011/11/03/jquery-1-7-released/

Upvotes: 6

Martin.
Martin.

Reputation: 10529

In case you're creating a javascript application for yourself or for your own product, you should use jQuery 1.7 and .on() method.

In case you're doing some kind of plugin, which can be used on older versions, I would use .delegate()

Upvotes: 1

rossipedia
rossipedia

Reputation: 59377

Starting with jQuery 1.7, it is recommended that all new code going forward use on() and off() for all event handling.

http://blog.jquery.com/2011/11/03/jquery-1-7-released/

Upvotes: 4

David Thomas
David Thomas

Reputation: 253318

As of jQuery 1.7 the jQuery team/API advise that:

[the] .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Reference: live() API reference, at: http://api.jquery.com/live/

So the choice, post jQuery 1.7, is between on() and delegate(); and the recommendation, above, seems to suggest that you should use .on() in preference to delegate(). Although I can't argue as to why that is.

Upvotes: 1

Related Questions