The examples in this article describe jQuery event binding and delegation. Share it with everyone for your reference. The specific method is as follows:
JQuery event binding and delegation can be implemented using a variety of methods, on() , bind() , live() , delegate() , and one().
Sometimes we may bind an event like this:
We can implement the above event binding in a variety of ways:
1. on()
Corresponding to on() is off(), which is used to remove event binding:
off(): remove the binding by on()
one(): only bind once.
2. bind()
Parameters:
(type,[data],function(eventObject))
type: A string containing one or more event types, with multiple events separated by spaces. For example, "click" or "submit", or a custom event name.
data: Additional data object passed to the event object as the event.data attribute value
fn: The handler function bound to the event of each matching element
(type,[data],false)
type: A string containing one or more event types, with multiple events separated by spaces. For example, "click" or "submit", or a custom event name.
data: Additional data object passed to the event object as the event.data attribute value
false: Setting the third parameter to false disables the default action.
Bind multiple event types at the same time:
Bind multiple event types/handlers simultaneously:
You can pass some additional data before event handling.
Cancel the default behavior and prevent the event from bubbling by returning false.
Problems with bind
If there are 10 columns and 500 rows in the table to which click events are bound, then finding and traversing 5000 cells will cause the script execution speed to slow down significantly, and saving 5000 td elements and corresponding event handlers will also Takes up a lot of memory (similar to having everyone physically stand at the door waiting for a delivery).
Based on the previous example, if we want to implement a simple photo album application, each page only displays thumbnails of 50 photos (50 cells), and the user clicks "Page x" (or "Next Page") link can dynamically load another 50 photos from the server via Ajax. In this case, it seems that binding events for 50 cells using the .bind() method is acceptable again.
This is not the case. Using the .bind() method will only bind click events to 50 cells on the first page. Cells in subsequent pages that are dynamically loaded will not have this click event. In other words, .bind() can only bind events to elements that already exist when it is called, and cannot bind events to elements that will be added in the future (similar to how new employees cannot receive express delivery).
Event delegation can solve the above two problems. Specific to the code, just use the .live() method newly added in jQuery 1.3 instead of the .bind() method:
So far, everything seems perfect. Unfortunately, this is not the case. Because the .live() method is not perfect, it has the following major shortcomings:
The $() function will find all td elements in the current page and create jQuery objects. However, this td element collection is not used when confirming the event target. Instead, a selector expression is used to compare with event.target or its ancestor elements, so Generating this jQuery object will cause unnecessary overhead;
By default, events are bound to the $(document) element. If the DOM nested structure is very deep, events bubbling through a large number of ancestor elements will cause performance losses;
It can only be placed after the directly selected element, and cannot be used after the consecutive DOM traversal method, that is, $("#info_table td").live... can be used, but $("#info_table").find("td" ).live...No;
Collect td elements and create jQuery objects, but the actual operation is the $(document) object, which is puzzling.
The solution
To avoid generating unnecessary jQuery objects, you can use a hack called "early delegation", which is to call .live() outside the $(document).ready() method:
Here, (function($){...})(jQuery) is an "anonymous function that is executed immediately", forming a closure to prevent naming conflicts. Inside the anonymous function, the $parameter refers to the jQuery object. This anonymous function does not wait until the DOM is ready before executing. Note that when using this hack, the script must be linked and/or executed in the head element of the page. The reason for choosing this timing is that the document element is available at this time, and the entire DOM is far from being generated; if the script is placed in front of the closing body tag, it makes no sense, because the DOM is fully available at that time.
In order to avoid performance losses caused by event bubbling, jQuery supports the use of a context parameter when using the .live() method starting from 1.4:
In this way, the "trustee" changes from the default $(document) to $("#info_table")[0], saving the bubbling trip. However, the context parameter used with .live() must be a separate DOM element, so the context object is specified here using $("#info_table")[0], which is obtained using the array index operator. A DOM element.
4. delegate()
As mentioned earlier, in order to break through the limitations of the single .bind() method and implement event delegation, jQuery 1.3 introduced the .live() method. Later, in order to solve the problem of too long "event propagation chain", jQuery 1.4 supported specifying context objects for the .live() method. In order to solve the problem of unnecessary generation of element collections, jQuery 1.4.2 simply introduced a new method.delegate().
Using .delegate(), the previous example can be written like this:
Using .delegate() has the following advantages (or solves the following problems of the .live() method):
Directly bind the target element selector ("td"), event ("click") and handler to the "dragee" $("#info_table"), without additional collection of elements, shortened event propagation path, and clear semantics;
Supports calling after the consecutive DOM traversal method, that is, supports $("table").find("#info").delegate..., supporting precise control;
It can be seen that the .delegate() method is a relatively perfect solution. But when the DOM structure is simple, .live() can also be used.
Tip: When using event delegation, if other event handlers registered on the target element use .stopPropagation() to prevent event propagation, the event delegation will become invalid.
undelegate(): Remove the binding of delegate
I hope this article will be helpful to everyone’s jQuery programming.