You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: page/events/history-of-events.md
+9Lines changed: 9 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -2,6 +2,7 @@
2
2
title: History of jQuery Events
3
3
level: intermediate
4
4
---
5
+
5
6
Throughout the evolution of jQuery the means of event binding has changed for various reasons ranging from performance to semantics. As of jQuery v1.7 the `.on()` method is the accepted means of both directly binding events and creating delegated events. This article aims to explore the history of *event delegation* from jQuery v1.0 to the present and how each version leverages it.
6
7
7
8
Given the following HTML, for our example we want to log the text of the each `<li>` to console whenever it is clicked.
@@ -19,6 +20,7 @@ Given the following HTML, for our example we want to log the text of the each `<
It is possible to use `.bind()` and attach a handler to every element.
@@ -29,13 +31,15 @@ It is possible to use `.bind()` and attach a handler to every element.
29
31
console.log( elem.text() );
30
32
});
31
33
```
34
+
32
35
As discussed in the [event delegation](/event/event-delegation) article, this is not optimal.
33
36
34
37
### liveQuery
35
38
*liveQuery* was a popular jQuery plugin that allowed for the creation of events which would be triggered for elements that existed now or in the future. This plugin did not use event delegation and used expensive CPU processing to poll the DOM for changes every 20ms and fire events accordingly.
Passing the *context* as a second optional argument to the `$()` function has been supported since v1.0. However support for using this *context* with the `$.live()` method was not added until v1.4.
In this instance when an `<li>` is clicked the event still bubbles all the way up the *document tree* as it did before. However, our event handler is now bound to the parent `<ul>` tag, so we do not have to wait for the event to bubble all the way up to the *document* root.
The `.delegate()` method provides a clear difference between the *context* of where to attach delegated event handler, and the *selector* to match when the event bubbles up to the delegated element.
The `.on()` method gives us a semantic approach for creating directly bound events as well as delegated events. It eliminates the need to use the deprecated `.bind()`, `.live()`, and `.delegate()` methods, providing a single API for creating events.
All of these ways of *event delegation* were innovative and considered a best practice at the time of their release. Depending on what version of jQuery you have implemented use the appropriate means of *event delegation*.
0 commit comments