JavaScript interview questions: event Delegate and this, javascriptthis
JavaScript is not only a low threshold, but also an interesting, powerful, and very important language. People from all walks of life find that their most messy choice is the scripting Script Programming Language. Because of various backgrounds, not everyone has a wide understanding of JavaScript and its basic principles. Generally, you come to book, unless you go to a job interview to think about why or how to do it, JavaScript is just what you work.
The objective of this category is to deeply explore some concepts and theories of JavaScript. The topic is from the list of typical JavaScript interview questions of Darcy Clarke. I hope that you will not only read this article for the answer, but each article will give you a new understanding of the knowledge you have learned in the past, or review what you have learned, this helps you implement all interactions with JavaScript.
Detailed event Delegation
Event delegation is an idea of responding to events by other elements rather than the event Target elements. UsedocumentAn example of event delegation is used to process button click operations.ulElement to process its child elementsli.
There are multiple ways to handle event delegation. The standard method comes from the features of the native browser. The browser processes events in a specific workflow and supports event capture and event bubbling. W3C documentation on how browsers support Events: W3C DOM Level 3 Events. Some JS libraries and frameworks expose other methods, such as the publish/subscribe model (as mentioned later ).
Event capture and event bubbling are two phases in the event stream. When an event is generated, click a button to start from the top container (generally the html root node ). The browser traverses the DOM tree until it finds the element that triggers the event. Once the browser finds the element, the event stream enters the event Target stage, the browser will bubble up along the DOM tree until the top-level container to see if other elements need to use the same event.
The following example shows the process. Clicking the button will cause the event stream to recognize the text in the container. Each element receives the same click listening code. Due to event capture, click events will first trigger the click handler bound to the HTML node, and then return to the top-level element at the end of the event bubble stage.
View this on JSFiddle
Most modern libraries use bubble listeners, which are processed in the capture phase. The Browser contains a method to manage event bubbles. The event handler can callstopPropagationTells the DOM event to stop bubbling. The second method is to callstopImmediatePropagationIt not only stops bubbling, but also prevents other handlers that listen to the current event on this element from triggering. However, be careful when stopping the propagation event, because you do not know whether there are other upper-level DOM elements that may need to know the current event.
There is also a third method that can control how elements respond to events. All modern browser supportpreventDefaultThis method will prevent the browser from handling the default behavior of the event. A common example is Link. Using a link to perform UI operations is a common practice. However, you can usepreventDefaultTo prevent this default action.
There are other methods for implementing event delegation, among which the release/subscription model is worth mentioning. The publishing/subscription model is also called the broadcast model, which involves two participants. Generally, two participants are not closely linked in the DOM and may be from a sibling container. You can set a listening handler for their common ancestor elements, but if the common ancestor elements are at a higher level in the DOM tree (close to the root node ), it will listen to events of many peer elements and lead to unexpected results. Of course, there may be logical or structural reasons to separate these two elements.
The publishing/subscription model can also customize events. The publishing/subscription model sends messages from an element and traverses them up. Sometimes, the DOM will notify all element events in the traversal path. In the following example, JQuery usestriggerMethod To pass events.
View this on JSFiddle
Using Event delegation to manage event streams has many advantages, the biggest of which is to improve performance. Each listener bound to the element occupies some memory. If there are only a few listeners on the page, we will not notice the differences between them. Then, if you want to listen to each cell in a table with 50 rows and 5 columns, your Web application will start to slow down. The best way to make the application run as quickly as possible is to keep the memory usage as low as possible.
Event delegation can reduce the number of listeners. Binding events to the element container requires only one listener. The disadvantage of this method is that the parent container's listener may need to check the event to select the correct operation, and the element itself is not a listener. The impact of additional processing is much lower than that of many listeners in memory.
Less listeners and less DOM interaction are easy to maintain. The parent container-level listener can handle multiple different event operations. This is a simple method to manage related event operations. These events usually need to perform relevant functions or share data.
If the parent container is a listener, perform independent internal operations without adding or removing the listener. Element operations are extremely common in single-page applications. Simply adding a button to a certain part also creates a potential performance block for the application without proper event delegation, you must manually add a listener for each button. If each listener is not cleaned up, it may cause memory leakage. The browser does not clean up the page, so in a single page application, all fragments improperly cleared from the memory will be left in the memory, these fragments will reduce program performance.
When adding interactions to the page, consider whether you really need to listen to elements.
Another article worth reading: Event Delegation In JavaScript
How does this work in JavaScript?
thisA common method of keyword in JavaScript is the current context of the Code.
- If
thisIf it is not set, it is directed to the global object by default, which is usuallywindow
- If a function runs an inline function, such as an event listener
thisPoint to the source code of the inline function. For example, when you set a button to click the handler,thisThe button in the anonymous function will be referenced.
- If a function is an object constructor,
thisPoint to the new object.
- If a function is defined on an object and then called,
thisPoint to this object.
In asynchronous programming,thisIt is easy to change a function operation in the process. A trick to keep the processing program context is to set it to a variable in the closure. When a function is called where the context changes, suchsetTimeoutYou can still reference the required object through this variable.
OperationthisAnother way is throughcall,applyAndbind. All three methods are used to call a function and specifythisYou can make the Code use the objects you specify, instead of relying on the browser to calculatethisPoint.Call,applyAndbindIt is quite complicated and should have its own document records. We will regard this as part of the problem to be resolved in the future. Below is a changethisExample of pointing to a method:
View this on JSFiddle
Event delegation andthisIt is an important function in modern JavaScript. Understanding their working principles is the key to successful product development, and it is certain that this is a must for JavaScript engineers.
Http://www.ido321.com/1570.html.
According to @ Nicolas Bevacqua's Translation of JavaScript Interview Questions: Event Delegation and This, the entire translation contains my own understanding and thoughts, if the translation is poor or there is something wrong, ask your colleagues for advice. If you need to reprint this translation, need to indicate the English Source: http://modernweb.com/2014/11/25/javascript-interview-questions-event-delegation/