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 department 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     Event delegation is a thought that responds to events resulting from other elements rather than event target elements. Using the document element to handle the button's click behavior is an example of an event delegate, and another common scenario is to use the UL element to handle the event of its child Li.     There are several ways to handle event delegation. 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 that starts 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.     Most modern libraries use bubbling snooping while processing in the capture phase. The browser contains a method to manage event bubbling. Event handlers can call Stoppropagation to tell DOM events to stop Stop bubbling, the second way is to call stopimmediatepropagation, 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 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 events. A common example is linking, which is a common practice for performing UI operations with links. However, when we do not want the link to open a new page in the new tab like the normal active link, you can use the Preventdefault method to block this 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 event through the trigger method.     Using event delegates to manage event streams has many advantages, the greatest of which is improved 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 element's container 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 less dom interaction 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 often requireRelated functions or need to share data.     If the parent container is a listener, then you need to perform a separate internal operation without adding or removing the listener itself. 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 you add interactivity to the page, think about whether you really need to listen to the elements.

This is how the This keyword works in JavaScript a common way in JavaScript is to refer 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, such as an event listener, is run in a function, This the source code that points to the inline function. For example , When you set a click handler for a button , This references the button within the anonymous function.
  • If the function is a constructor for an object, This point to the new object.
  • If the function is defined on an object , then when the object is called , This point to the object.
In asynchronous programming, this can easily 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 changes, such as settimeout, you can still refer to the desired object by that variable. Another way to manipulate this is through call, apply, and bind. Three methods are used to invoke a function, and can specify the context of this, you can let the code use the object you specify, rather than rely on the browser to calculate what this point. Call, apply, and bind itself are quite complex and should have their own documentation, and we'll take that as part of the future problem. Here's an example of how this approach can be changed: event delegates and this are important features in modern JavaScript, and understanding how they work is key to successful product development and, to be sure, is something that a JavaScript engineer needs to understand.

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.