JavaScript Interview questions: event delegate and this

Source: Internet
Author: User
Tags event listener

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 of the variety of backgrounds, not everyone has a broad understanding of JavaScript and its rationale. Usually carcass, unless you go to a job interview to think about why or what to do, otherwise JavaScript is just the content of your work.

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

Detailed Event delegation

An event delegate is a thought that responds to an event's behavior by other elements rather than by an event target element. Using document elements to handle the click behavior of a button is an example of an event delegate, and another common scenario is to use an ul element to manipulate the events of its child elements li .

There are several ways to handle event delegates. The standard approach comes from native browser functionality. The browser processes events in a specific workflow and supports event capture and event bubbling. A document about how browsers support events: The Web DOM Level 3 events. 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 in the event flow, when any event occurs, such as clicking a button, starting at the topmost container (typically the root node of the HTML). The browser walks down the DOM tree until it finds the element that triggered the event, and once the browser finds the element, the event stream enters the event target stage, and after that phase is complete, the browser bubbles up the DOM tree up to the topmost container to see if any other elements need to use the same event.

The following example illustrates this process. Clicking the button causes the event stream to identify itself under the container text, each element receives the same click-through code, because of event capture, the Click event will first trigger the HTML node bound click Handler, and then return to the topmost element at the end of the event bubbling phase.

View this on Jsfiddle

Most modern libraries use bubbling snooping while processing in the capture phase. The browser contains a method to manage event bubbling. The event handler can call to stopPropagation tell DOM events to stop bubbling, and the second is stopImmediatePropagation to call, which not only stops bubbling, but also prevents other handlers on the element that are listening for the current event from triggering. However, be careful when you stop propagating events, because you don't know if there are other DOM elements in the upper layer that might need to know about the current event.

There is also a third way to control how elements react to events. All modern browser support preventDefault methods, this method prevents the browser from handling the default behavior of events. A common example is linking, which is a common practice for performing UI operations with links. However, when we don't want the link to open a new page in a new tab like a regular active link, you can use the preventDefault method to block the default behavior.

There are other ways to implement event delegation that can be considered, which is worth mentioning is the Publish/subscribe model. The Publish/subscribe model is also known as the broadcast model, involving two participants. Typically, two participants are not closely linked in the DOM, and may be from a sibling's container. It is possible to set up a listener handler for their common ancestor elements, but if the common ancestor elements are at a higher level in the DOM tree (near the root node), they will listen to events of many sibling elements, which can cause unexpected results; Of course, there may be logical or structural reasons to separate the two elements.

The Publish/Subscribe model can also customize events. The Publish/Subscribe model sends a message from an element and traverses it up and down, sometimes down, and the DOM notifies all elements on the traversal path that the event has occurred. In the following example, jquery passes the trigger event through a method.

View this on Jsfiddle

There are many advantages to using event delegates to manage event streams, the greatest of which is improving performance. Each listener that binds to the element consumes some memory, and if there are only a few listeners on the page, we will not notice the difference between them, and then if you listen to each cell in a table with 50 rows and 5 columns, your Web app will start to slow down, The best way to make your application run the fastest is to keep memory usage as low as possible.

Using event delegation can reduce the number of listeners, and binding an event on the container of an element means that only one listener is needed. The disadvantage of this approach is that the listener for 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 additional processing is much lower than in many in-memory listeners.

Fewer listeners and fewer Dom interactions are also easy to maintain. The listener at the parent container level can handle a number of different event operations, which is an easy way to manage related event operations that typically require the execution of related functions or the need to share data.

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

When adding interactivity to a page, think about whether you really need to listen to the elements.

Another article worth reading: Event delegation in JavaScript

How this works in JavaScript

thisA common way to use keywords in javascript is to refer to the current context of the code.

    • If this not set, the default point is to the global object, which is usuallywindow
    • If an inline function, such as an event listener, is run in a function, it this points to the source code of the inline function. For example, when you set a click handler for a button, the this button within the anonymous function is referenced.
    • If the function is a constructor for an object, point to the this new object.
    • If the function is defined on an object and then the object is called, this point to that object.

In asynchronous programming, this it is easy to change a function operation in the process. A small trick to keeping the context of a handler is to set it to a variable within the closure, and when a function is called where the context is changing, setTimeout you can still refer to the desired object through that variable, for example.

thisanother way to operate is through call , apply and bind . Three methods are used to invoke a function and can specify this the context, you can let the code use the object you specified, rather than rely on the browser to calculate the this point to what. Call, apply and bind itself is quite complex, should have its own documentation, and we will consider this as part of the future problem to be solved. Here is an this example of how to change the pointer method:

View this on Jsfiddle

Event delegation and this being an important feature in modern JavaScript, understanding how they work is key to successful product development and, to be sure, this is something that a JavaScript engineer must understand.

Source: http://www.ido321.com/1570.html

This article is based on @nicolas Bevacqua's "JavaScript interview Questions:event delegation and this", the whole translation with my own understanding and thinking, If the translation is not good or wrong, please peer friends pointing. If you want to reprint this translation, please specify the English source: http://modernweb.com/2014/11/25/javascript-interview-questions-event-delegation/

JavaScript Interview questions: event delegate and this

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.