Event delegates and this face questions in JavaScript

Source: Internet
Author: User
Tags event listener memory usage tagname


JavaScript is not only a low threshold, but also an interesting, powerful and very important language. People from all walks of life find their most confusing choice is the Javasscript programming language. Because there are all kinds of backgrounds, not everyone has a broad understanding of JavaScript and its rationale. Usually book, unless you go to a job interview to think about why or how to do it, JavaScript is just the content of your work.

The goal of this series is to delve into some of the concepts and theories of JavaScript. The theme comes from Darcy Clarke's list of typical JavaScript interview questions. Hopefully you're not just reading this article for the sake of the answer, each article will give you a new understanding of what you've learned in the past, or revisit what you're learning, which helps you achieve all the interactions with JavaScript.

Detailed Event delegation

An event delegate is an idea that responds to an event-generated behavior by other elements rather than by an event target element. Using the document element to handle the button's click behavior is an example of an event delegate, another common case is to use the UL element to handle its child element Li's event.

There are several ways to handle event delegates. The standard approach comes from the functionality of native browsers. Browsers handle events in a specific workflow and support event capture and event bubbling. The document of the Web Consortium about how browsers support events: The 3 events of the DOM level. Some JS libraries and frameworks expose other ways, such as the Publish/subscribe model (which will be mentioned later).

Event capture and event bubbling are two stages of an event flow, and when any event is generated, such as clicking a button, it starts at the top of the container (typically the root node of the HTML). The browser goes down through the DOM tree until it finds the element that triggers the event, and once the browser finds the element, the event stream enters the event target phase, and after that phase is completed, the browser bubbles up through the DOM tree until the topmost container to see if there are other elements that need to use the same event.

The following example illustrates this process. Clicking on the button causes the event stream to identify itself in the text below the container, each element receiving the same click-through code, and as a result of event capture, the Click event triggers the HTML node-bound Click handler First, then returns to the topmost element at the end of the event bubbling phase.

var nodes = $ (' * '),
node = {};
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];

Node.addeventlistener (' click ', Function (event) {
$ (' #EventListing '). Append (' Bubble ' + (event.currentTarget.id | | event.currentTarget.tagName) + ' <br/> ');
});

Node.addeventlistener (' click ', Function (event) {
if (event.currenttarget!= event.target) {
$ (' #EventListing '). Append (' Capture ' + (event.currentTarget.id | | event.currentTarget.tagName) + ' <br/> ');
}
}, True);
}


Most modern libraries use bubbling listening, which is handled during the capture phase. The browser contains a method to manage event bubbling. The event handler can call Stoppropagation to tell the DOM event to stop bubbling, and the second way is to call stopimmediatepropagation, which not only stops bubbling, it also blocks other handlers on the element that are listening for the current event to trigger. However, be careful when you stop propagating events, because you don't know if there are other upper-level DOM elements that might need to know the current event.

There is also a third way to control how elements react to events. All modern browsers support the Preventdefault method, which prevents the browser from handling the default behavior of the event. A common example is linking, which is a common practice for performing UI operations using links. However, when we do not want the link to open a new page on a new tab like a normally activated link, you can use the Preventdefault method to block this default behavior.

There are other ways to implement event delegation, which is worth mentioning is the Publish/subscribe model. The Publish/Subscribe model is also called the broadcast model, involving two participants. Typically, two participants do not have a close connection in the DOM, and may be a container from a sibling. You can set up a listener handler for their common ancestor elements, but if the common ancestor element is at a higher level in the DOM tree (closer to the root node), it listens for events of many sibling elements, which can cause unexpected results; there may be logical or structural reasons for separating the two elements, of course.

The Publish/Subscribe model can also customize events. The Publish/Subscribe model sends messages from one element and iterates up, sometimes down, and the DOM notifies all element events on the traversal path to occur. In the following example, jquery passes events through the trigger method.

$ (' #container '). On (' Mycustomevent ', function (e, data) {
$ (' #insertText '). append (data);
});

$ (' #button2 '). Click (function () {
$ (' #button2 '). Trigger (' mycustomevent ', [' I triggered ']);
});

There are many advantages to using event delegates to manage event streams, with the greatest advantage being improved performance. Each listener of an element binding consumes some memory, and if there are only a few listeners on the page, we don't notice the difference, and then if you listen to each cell in a table of 50 rows and 5 columns, your Web application starts to slow down, The best way to make your application run fastest is to maintain the lowest possible memory usage.

Using event delegates reduces the number of listeners, and binding events in the container of an element means that only one listener is required. The disadvantage of this approach is that the listener of the parent container may need to check the event to select the correct action, and the element itself will not be a listener. The impact of extra processing is much lower than that of many listeners in memory.

Fewer listeners and fewer Dom interactions are also easy to maintain. A parent container-level listener can handle many different event actions, an easy way to manage related event actions, which typically require performing related functions or needing to share data.

If the parent container is a listener, then perform a separate internal operation without having to add or remove its own listener. Element operations are extremely common in single page applications, adding a button to a section can also create a potential performance block for your application, and without proper event delegation, you must manually add a listener to each button, which can cause a memory leak if each listener is not cleaned up. The browser does not clean the page, so in a single page application, all of the pieces that are cleaned out of memory are left in memory, which degrades program performance.

When adding interactivity to a page, consider carefully whether you really need to listen to the elements.


This is how it works in JavaScript

This keyword is a common method in JavaScript that refers to the current context of the code.

If this is not set, the default point is to the global object, which is usually window
If an inline function is running in a function, such as an event listener, this points to the source code of the inline function. For example, when you set a button's click Handler, this refers to the button inside the anonymous function.
If the function is a constructor of an object, this points to the new object.
If the function is defined on an object, and then the object is called, this points to the object.
In asynchronous programming, this makes it easy to change a feature operation in the process. A trick to keep the handler context is to set it to a variable within the closure, and you can still refer to the desired object through the variable when a function is invoked in the context of the change, such as settimeout.

Another way to operate this is through call, apply, and bind. All three methods are used to invoke a function, and to specify the context of this, you can have the code use the object you specify, rather than relying on the browser to figure out what this points to. Call, apply, and bind are inherently complex and should have their own documentation, and we'll take that as part of future problems. Here is an example of a change to this point method:

var div = $ (' #appendHere ');

$ (' #clickMe '). On (' click ', function () {
var that = this;
Div.append (Checkforwindow (this));

settimeout (function () {
Div.append (Checkforwindow (this));
Div.append (' <strong>that</strong> is ' + that.tagname + ' <br/> ');
}, 300);
});


function Checkforwindow (Elm) {
if (Elm instanceof Window) {
Return ' This is the window<br/> ';
else if (elm.tagname) {
Return (' It is the ' + elm.tagname + ' <br/> ');
} else {
Return (' It is ' + Elm + ' <br/> ');
}
}

Event delegates and this are important features of modern JavaScript, and understanding how they work is key to successful product development and, to be sure, this is what JavaScript engineers have to understand

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.