jQuery 1.7 .on() method, why is it necessary?
Asked Answered
T

5

5

I don't understand why this method exists....

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

It seems to me you'd always just do $(el).click() instead of $(el).on('click', function...

Trin answered 3/11, 2011 at 22:54 Comment(0)
H
4

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

Hillside answered 3/11, 2011 at 23:0 Comment(0)
J
2

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.

Jihad answered 3/11, 2011 at 22:57 Comment(2)
You could bind a single function to more than one event type with the other functions too. This is a unification of event handling, and it also allows you to assign more than one function to more than one event via the mapping.Beachcomber
Sure, but not with .click() which was specifically mentioned!Jihad
I
2

$(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().

Itu answered 3/11, 2011 at 23:6 Comment(0)
S
1

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.

Sesquiplane answered 3/11, 2011 at 23:5 Comment(0)
B
0

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)

Beachcomber answered 3/11, 2011 at 22:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.