JS event bubbling and the details of the event delegation

Source: Internet
Author: User

JS Event bubbling

JS So-called event bubbling is a child element of an event is triggered, its ancestor element of the event is also recursive execution

Html:

<ul class= "Clearfix" data-type= "Citypick" >
<li class= "active_sort_opts" data-id= "0" > All </li>
<li data-id= > New York </li>
<li data-id= "119" > Los Angeles </li>
<li data-id= "138" > Las Vegas </li>
<li data-id= > Hawaii </li>
<li data-id= > San Francisco </li>
<li data-id= > Orlando </li>
<li data-id= "118" > Seattle </li>
</ul>

Js:


$ ("ul[data-type= ' Citypick ']"). On (' click ', function () {
Alert ("Parent element ul is clicked");
});
$ ("ul[data-type= ' Citypick ']"). On (' Click ', ' Li ', function () {
Alert ("child element Li is clicked");
});
When Li's Click event is triggered, the parent UL Click event is also triggered to execute,

And on some occasions we do not want it to bubble, how to do it? Simple!

Js:


$ ("ul[data-type= ' Citypick ']"). On (' click ', function () {
Alert ("Parent element ul is clicked");
});
$ ("ul[data-type= ' Citypick ']"). On (' Click ', ' Li ', function (e) {
E.stoppropagation ()//block bubbling
Alert ("child element Li is clicked");
});


Plus e.stoppropagation (); This sentence will stop the event bubbling.

JS Event Delegate

JS event delegate, in fact, using the principle of bubbling, starting from the clicked element, recursively propagating events to the parent element, the advantage of this is that for a large number of elements to be processed, there is no need to bind events for each element, just a binding of their parent elements to improve performance. Another benefit is that you can handle the elements that are dynamically inserted into the DOM, and the way you bind directly is not possible.
The event target itself does not handle the event, but instead delegates the processing task to its parent element or ancestor element, and even the root element event delegate exploits the "event bubbling" well. When a child element is clicked, the parent element of the child element captures the Click event and triggers its own method, depending on event bubbling.
See examples:
If there are now 10 buttons, to bind a click event for each button, it may only be 10 buttons, you can bind either one or the loop, but what about the performance?
Html:


<div class= "Button-group" >
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
<bottoun type= "button" class= "BTN" > Submit </bottoun>
</div>

Js:

$ (". Button-group"). On (' click ', '. Btn ', function () {
Alert ($ (this). html ());
});
As you can see, we're just binding the Click event for all the button's parent, rather than all the button-bound events, which greatly improves performance, and the benefits of this are the ability to process dynamically added elements

Is that there is a button the original DOM inside is not, is that you add in the other way, that is, the future element, with the direct binding method is not successful, can only use the event delegate, delegated to the element's parent to handle

Because event delegates are implemented through event bubbling, the event delegate will also fail if the child's elements prevent event bubbling!

In fact, the Jqueryjquery 1.7 Beta 1 has been available for binding and delegate events. Bind (),. Live () and. Delegate () methods, which can be said to be improved step-by-step,

Assuming there is a multiple-row, multiple-column table, we want the user to click each cell to see more information about the content (for example, through the cue bar). To do this, you can bind the click event for each cell:

$ ("info_table TD"). BIND ("click", Function () {/* Show more info/});

The problem is that if there are 10 columns and 500 rows in the table that you want to bind the event to, then finding and traversing 5,000 cells can cause the script to perform significantly slower, while saving 5,000 TD elements and corresponding event handlers can also consume a lot of memory
Event delegates can resolve both of these issues. On the code, just replace the. bind () method with the new. Live () Method of jquery 1.3:

$ ("#info_table TD"). Live ("Click", Function () {/* Show more info/});

Here the. Live () method binds the Click event to the $ (document) object (but this is not reflected in the code, which is also.) One of the main reasons for the live () method being criticized in detail later, and only need to give $ (document) Bind once (not 50 times, not 5,000 times). When any event is received, the $ (document) object checks the event type and the event target, and executes the handler that is delegated to it if it is the click event and the event target is TD.
Everything seems to be perfect. Unfortunately, that is not the case. Because the live () method is not perfect, it has several major drawbacks:
The $ () function finds all the TD elements in the current page and creates the jquery object, but does not use this set of TD elements 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 can cause unnecessary overhead;
By default, events are bound to the $ (document) element, and if the DOM nesting structure is deep, event bubbling through a large number of ancestor elements can result in performance loss;
Can only be placed after a directly selected element and cannot be used after the consonant dom traversal method, that is $ ("#infotable TD"). Live ... Yes, but $ ("#infotable"). Find ("TD"). Live ... No

It is puzzling to collect TD elements and create jquery objects, but the actual operation is the $ (document) object.
In order to avoid the performance loss caused by event bubbling, jquery supports the use of the. Live () method in conjunction with a context parameter from 1.4:
$ ("TD", $ ("#info_table") [0]). Live ("Click", Function () {/* Show more info/});

In this way, the "trustee" becomes $ ("#infotable") from the default of $ (document) [0], saving the bubbling journey.
. Delegate ()
As mentioned earlier, JQuery 1.3 introduces the. Live () method in order to overcome the limitations of the single. bind () method and implement the event delegate. Later, in order to solve the problem of "event propagation chain" too long, jQuery 1.4 also supports specifying a context object for the. Live () method. In order to solve the problem of unnecessary generation of element sets, JQuery 1.4.2 simply introduced a new method. Delegate ().
Using. Delegate (), the preceding example can be written like this:

$ ("#info_table"). Delegate ("TD", "click", Function () {/* Show more info/});

JQuery 1.7 To resolve the inconsistency caused by the coexistence of bind (),. Live () and. Delegate () will add a new pair of event methods:. On () and. Off ():

$ (Elems). On (events, selector, data, FN);
$ (elems). Off (events, selector, FN);

If selector is specified, the event delegate, otherwise, is the general binding.
So now just use the on method and recommend the on method for delegates or general binding events

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.