jQuery 1.7: converting event shortcuts, such as click(), to on()?
Asked Answered
T

2

9

I just found out that jQuery 1.7 introduced a new method, on(). With my brief study, I see it as a consolidated way to bind events, as opposed to decide which one of bind(), live(), and delegate() to use. IMO, this is a really nice addition that offers numerous benefits. But then I am not sure if I need to convert event shortcuts, such as click(). According to the official document, the definition of click() is still the shortcut to .bind('click', handler). I thought it would make more sense for the jQuery developers to redefine click() and other event shortcuts in v1.7+ to use on(), no?

Tomika answered 30/11, 2011 at 10:14 Comment(0)
J
5

jQuery documentation is clearly presenting .click() as a shorthand of .on("click"), so I guess you can replace all your previous calls, if you want.

Extract of the on() method documentation:

There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

The method .on() actually does the same as .bind() except that you can bind multiple events at once, and select a set of children that actually fire this event.

I don't think it makes more sense to use on() instead of click() unless you need to bind multiple events or do some more tricky stuff with filtering children.

Jaw answered 30/11, 2011 at 10:40 Comment(0)
P
1

ghusse is right, there is no need to replace all of your .click() shortcuts with .on(), but you should replace your .live() code with .on() because .live() is marked as deprecated and might as well be removed with jQuery 1.8 ... discussion is ongoing.

$('SELECTOR').live('click', function(e) { ... });

$('UPSELECTOR').on('click', 'SELECTOR', function(e) { ... });

Where UPSELECTOR is either the same as SELECTOR (then you can omit the second parameter of .on()) or it represents a (set of) element(s) higher in the DOM tree, i.e. element(s) that will be traversed when the event is bubbling. A common choice here would be document or body

Purplish answered 30/11, 2011 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.