I don't understand why this method exists....
It seems to me you'd always just do $(el).click()
instead of $(el).on('click', function...
I don't understand why this method exists....
It seems to me you'd always just do $(el).click()
instead of $(el).on('click', function...
$(el).on
gives the developers an unified way of binding events for any event types, direct and delegated events. It also allows you to bind more than one events at the same time by passing an object (2nd example in the documentation)
You also save a few keystrokes, for what it's worth.
With .on()
you can bind more than one event type at the same time, so you don't have to duplicate code or create a separate function if you want to do the same thing on multiple events.
.click()
which was specifically mentioned! –
Jihad $(el).click(...)
is shorthand for $(el).bind('click', ...)
. If you compare the documentation for bind()
to the documentation for on()
, you'll see a number of differences.
This is pretty well summarized by the first paragraph of the bind()
docs:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
It's my understanding that the new .on()
is a merging of somewhat duplicate functionality in .bind()
, .delegate()
and .live()
. It is as much a merging of the API as it is a combining of the implementations into a more unified implementation.
It looks to me like it's being staged to combine/replace the various other event binding functions...One Function To Bind Them All! (LOTR geekery ftw)
© 2022 - 2024 — McMap. All rights reserved.