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?
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.
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
© 2022 - 2024 — McMap. All rights reserved.