Technical principles of JavaScript event delegation

Source: Internet
Author: User
Tags event listener tag name

One of the hottest technologies in today's JavaScript technology World is ' event delegation '. Using Event delegation techniques allows you to avoid adding event listeners to a particular node, and instead, event listeners are added to their parent elements. The event listener parses events bubbling up from child elements to find out which child element is the event. The basic concept is simple, but there are still a lot of people who don't understand how event delegates work. Here I will explain how event delegation works and provide examples of basic event delegates for a few pure JavaScript.

Suppose we have an UL element that has several child elements:

<ulID= "Parent-list">    <LiID= "Post-1">Item 1</Li>    <LiID= "Post-2">Item 2</Li>    <LiID= "Post-3">Item 3</Li>    <LiID= "Post-4">Item 4</Li>    <binID= "Post-5">Item 5</Li>    <LiID= "Post-6">Item 6</Li></ul>

We also assume that when each child element is clicked, it will have its own different events occurring. You can li add event listeners to each individual element, but sometimes these li elements may be deleted, there may be new additions, and listening to their new or deleted events will be a nightmare, especially if the code for your listener event is placed in another place in the app. But what if you put the listener on their parent element? How can you tell if the child element was clicked?

Simple: When the event of a child element bubbles to the parent ul element, you can check the target property of the event object and capture a reference to the node element that is actually clicked. Here is a very simple JavaScript code that demonstrates the process of event delegation:

// Find parent element, add Listener ... document.getElementById ("Parent-list"). AddEventListener ("click",function(e) {    // E.target is the element to be clicked!    // if the LI element    is clicked if (e.target && E.target.nodename = = "LI")        {//  find target, output id!        Console.log ("List item", E.target.id.replace ("post-"), "was clicked!" );    }});

The first step is to add an event listener to the parent element. When there are events that trigger the listener, check the source of the event and exclude non- li child element events. If it's an li element, we'll find the target! If it is not an li element, the event is ignored. This example is very simple, UL and li is a standard parent-child collocation. Let's experiment with some of the more diverse elements that match. Let's say we have a parent element with a div lot of child elements, but what we care about is a tag with the "ClassA" CSS class in it:

//get parent Element div, add Listener ...document.getElementById ("Mydiv"). AddEventListener ("click",function(e) {//E.target is the clicked element    if(e.target && E.target.nodename = = "A") {        //get CSS class name        varClasses = E.target.classname.split (""); //Search matches!        if(classes) {//For every CSS class The element has ...             for(varx = 0; x < classes.length; X + +) {                //If It has the CSS class we want ...                if(Classes[x] = = "ClassA") {                    //bingo!Console.log ("Anchor element clicked!"); //Now does something here ... .                }            }        }    }});

The above example not only compares the tag name, but also compares the CSS class name. Although a little more complicated, but still very representative. For example, if there is a tag in a tag span , this span will be the target element. At this point, we need to get back to the DOM tree structure and find out if there is a A.CLASSA element in it.

Because most programmers use a tool library such as jquery to handle DOM elements and events, I recommend that you use the event delegation method inside, because the tool library here provides advanced delegation methods and element screening methods.

Hopefully this article will help you understand the behind-the-scenes principles of JavaScript event delegation, and hopefully you will also feel the power of event delegation!

(English: Davidwalsh.)

Traditional event handling

An event delegate is the use of an event on one page to manage multiple types of events. This is not a new idea, but it is important for mastering performance. Typically, you'll see this code in the Web application:document.getElementById ("HELP-BTN"). onclick =function(event) {openhelp ();};
document.getElementById ("SAVE-BTN"). onclick =function(event) {savedocument ();};
document.getElementById ("UNDO-BTN"). onclick =function(event) {undochanges ();}; 

This traditional coding method assigns individual event-handling methods to each element. This is possible for sites with fewer interactions. However, for large wen applications, when there is a lot of event handling, it becomes unresponsive. The focus here is not on speed, but on memory consumption. If there are hundreds of interactions, the DOM element and the JavaScript code will have hundreds of associations. The more memory a web app needs to consume, the slower it will respond. Event delegation can reduce this problem.

 event bubbling and capturingIf the following properties were not the event, the event delegate would be possible. Early web development, browser vendors have a hard time answering a philosophical question: which element are you really interested in when you click on an area of the page? This problem brings about the definition of interaction. Clicking within the bounds of an element appears somewhat vague. After all, a click on one element also occurs within the bounds of another element. For example, click a button. You actually clicked on the button area, the area of the body element, and the area of the HTML element.

With this problem, the two main browsers Netscape and IE have different solutions. Netscape defines a processing method called event capture, which occurs first in the top-level object (document) of the DOM tree and then propagates toward the deepest element. In the legend, the event capture occurs first on the document, then the HTML element, the BODY element, and finally the button element.

IE is handled in the opposite way. They define a method called event bubbling. Event bubbling considers the deepest element of an event's promotion to receive the event first. Then it's the parent element, which, in turn, knows that the document object eventually receives the event. Although document has no independent visual representation relative to the HTML element, he is still the parent element of the HTML element and the event can bubble to the document element. So in the legend, oh Oh the button element receives the event first, then the body, and the HTML finally the document.   when defining the DOM, it is obvious that the two scenarios have their merits, so both scenarios are defined in the DOM Level 2 event specification. The document element first obtains the event, and then the capture stage propagates to the element most relevant to the event, when the event is captured by this element and then bubbled to the document element. The AddEventListener () method accepts three parameters: event name, event handler, a Boolean value that specifies whether the event is processed during the capture phase or during the bubbling phase. Most Web developers will use false as the third parameter, just like attachevent () in IE. Bubbling phase Handler
Document.addeventlistener ("click", Handleclick,false);
//capturing Phase Handler
Document.addeventlistener ("click", Handleclick,true);


implementing event delegates through bubblingThe key to event delegation is to process events at the highest level (usually document) by bubbling. Not all events support bubbling, but mouse and keyboard events are supported, and that's what you care about. Looking back at the previous example, you can handle all the click events by assigning an event to the document, and you only need to determine how the event is handled by distinguishing the nodes.


Document.onclick =function(event) {
//ie doesn ' t pass in the event object
Event = Event | | window.event;

//ie uses srcelement as the target
vartarget = Event.target | | Event.srcelement;

Switch(target.id) {
Case"HELP-BTN":
Openhelp ();
Break;
Case"SAVE-BTN":
SaveDocument ();
Break;
Case"UNDO-BTN":
Undochanges ();
Break;
//others?
}
};

With event delegates, several event handlers can be managed using a function. All the click events are delegated to a suitable function to handle. Similarly,MouseDown, mouseup, mousemove, mouseover, mouseout, DblClick , keyup, KeyDown, and keypress events can also be handled as such. However, MouseOver and mouseout are handled differently in event delegates and are considered "out" when the mouse moves from one element to its child elements.

 Note: You can also use event capture to complete event delegation, but this can only be used in non-IE browsers that support event capture.  AdvantagesThere are several advantages to the performance of the Web application for event delegation:1. Fewer functions to manage2. Less memory is consumedLess association between 3.javascript code and DOM structure4. When changing the innerHTML in the DOM structure, you do not need to change the event handler function moving from a traditional event-handling approach to event delegation improves the performance of large Web applications. Because it is so important, some of the JavaScript libraries, like Yui and Jquey, are also beginning to apply event delegates to their core interfaces. It's easy to implement event delegation, but it can bring a lot of performance improvements. This is especially true when you integrate dozens of event handlers into a function. Try the event delegate, and you will no longer use the traditional event-handling method.

Technical principles of JavaScript event delegation

Related Article

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.