JavaScript Interview Questions:event delegation and this

Source: Internet
Author: User
Tags event listener tagname

David Posin helps you land this next programming position by understanding important JavaScript fundamentals.

JavaScript is a fun, powerful, and important language with a low barrier of entry. People from all kinds of backgrounds and careers find themselves choosing to wrestle with the chaos, is JavaScript Pro Gramming. With such a varied set of backgrounds, does everyone has the same broad knowledge of JavaScript and its fundamentals. Often, it's not until your find yourself interviewing for a job so you really stop to consider why, or how, the stuff tha T usually just works, works.

The goal of this series would be is to delve into the concepts and theories that make up JavaScript. The topics would come from Darcy Clarke ' s awesome list of typical JS interview questions. Hopefully, you'll finish the article with more than just a answer to the question. Each article would leave you with a new understanding, or a brush-up from your past learnings, which would help R interactions with JavaScript.

Explain Event Delegation

Event delegation is the idea, something, and than the target of an action resolves the event raised by that action. An example of event delegation would is having the document element handle the Click action of a button. A fairly common occurrence, is to has a "UL" element handle the events raised by its children "Li" elements.

Event delegation can handled in several ways. The standard-of-the-derived from native browser functionality. Browsers is programmed to handle events in a particular work flow. They is designed to the support event capturing and event bubbling. The documentation on how browsers is to support events can is found HERE:W3C DOM level 3 events. Some JS Libraries and frameworks expose additional options such as the PUB/SUB model (which we'll look at below).

Event capturing and event bubbling is phases in a three phase flow. Any event this occurs, such as clicking a button, starts at the topmost container (which usually is the HTML root node). The browser moves down the DOM hierarchy until it finds the element raising the event. Once The browser finds the element that caused the event, it enters the targeting phase. Once targeting is complete, the browser bubbles up the DOM back to the topmost container to see if anything else needs to Use the same event.

The fiddle below illustrates the process. Clicking on either button would cause the event flow to identify itself in the text below the container box. Each element receives the same click Listener code. The Click event First fires at the HTML node with the capturing phase, and then returns to the top at the end of the BUBBL e phase.

<DivID= "Containerouter"style= "border:1px solid black; width:100px; padding:20px">    <DivID= "Containerinner"style= "border:1px solid black; width:80px; padding:10px">        <ButtonID= "Button1">1</Button>        <ButtonID= "Button2">2</Button>    </Div></Div><BR/><DivID= "Eventlisting"></Div>
AR nodes = $ (' * '), node= {}; for(vari = 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);}

View this on Jsfiddle

Fiddle Code explanation
The code starts by grabbing all nodes in the window. After getting a handle-nodes, the code loops through the each node and attaches a click handler to each element. Event though only the button can invoke a click event by default, the Click event still follows the expected capture (down ) and bubbling (up) event flow. The AddEventListener with the true parameter are the one setting up the capture listener, and the one without the extra par Ameter sets the bubbling listener.

Most modern libraries use the bubble phase for listener handling over the capture phase. Browsers include a-a-manage how high we want the event to bubble. An event handler can call Stoppropagation to tell the event to cease bubbling up the DOM. There is a second option called Stopimmediatepropagation. This method stops the bubbling, and would also stop any other listeners for this event on this element from firing. However, be careful when stopping propagation since you don ' t really know if there are anything else up the DOM that might Want to be aware of the event.

There is a third function worth knowing the can be called to control how elements react to events. All modern browsers support the Preventdefault function. This function prevents the browser from using its native operations to handle the event. A Common use case is the link. The Using links to perform UI operations is a common practice. However, we don ' t want that link to try activating the regular link function of the opening the page to a new page. Using Preventdefault stops the browser from trying to follow an href tag.

There is delegation methods to consider as well. One worth mentioning is the PUB/SUB model. The publication/subscription model, also called a radio model, involves and participants. Usually, the participants is not closely connected in the DOM, and may actually is derived from sibling containers. One could put a listener on the element they both ultimately descend from, and if the shared ancestor element is very high Then you could end up listening for too many events at the level and create the dreaded monolith mentioned earlier. Also, there may is logically or architectural reasons to keep the elements separate.

The Pub/sub model also opens the opportunity to create custom events. The PUB/SUB model works by sending a message out from one element and traveling up, and sometimes down, the DOM telling al L elements along the "the" the "the" event happened. JQuery uses the trigger function to pass events up the DOM as illustrated in the fiddle below.

<BR/><DivID= "Container"style= "border:1px solid black; width:100px; padding:20px">    <ButtonID= "Button2">Trigger Me</Button>    <DivID= "InsertText"style= "padding:10px;"></Div></Div><BR/><DivID= "Eventlisting"></Div>
function (E, data) {    $ (' #insertText '). append (data);}); $ (' #button2 '). Click (function  () {    $ (' #button2 '). Trigger (' mycustomevent ', [' I triggered ') ]);});

Fiddle Code Explanation
The first clause, $ (' #container '), sets a listener for the Mycustomevent event on the element. The second clause adds a click Listener on the $ (' button2 ') element. When the button was clicked it triggers the mycustomevent which bubbles up the DOM.

The is several benefits of using event delegation to manage the event flow. One of the biggest is performance. Every listener attached to a element takes up some memory. If there is only a few listeners on a page then the difference won ' t is noticed. However, if you had a listener on every cell of a in a Row 5 column table then your Web application could begin to slow down. In the interest of making a application as fast as possible it is best to keep memory with as low as possible.

Using Event Delegation can reduce the number of listeners from many to a few. Placing a listener on a container above the elements firing the event means only needing one listener. The drawback to this approach is and the listener at the parent container could need to examine the event to choose the Cor Rect operation, whereas a listener on the element itself would not. The impact of that extra processing was much less than the impact of too many listeners in memory.

Fewer listeners and fewer points of DOM interaction make for easier maintenance. One listener at a container level can handle multiple different event operations. This isn't an excuse for a monolithic function of titanic proportions. It is a easy-to-manage related events, often perform related functions or need to share data.

If A parent container is listening then individual operations performed inside that container don ' t has to add or Remo ve listeners on their own. Operations like dynamic buttons and elements is extremely common with the increased use of a single page applications. Something as simple as adding a button dynamically to a sections can create a potential performance block for your Applicat Ion. Without proper event delegation it becomes necessary to manually add listeners to each new button, and if all listener is Not cleaned up properly, it can potentially cause memory leaks. The browser does isn't clear the page, and therefore memory, in a single page application so everything that's not cleaned From memory properly can stick around. These fragments in memory drag down the performance of your application, like a great sponge, continues to absorb memo Ry growing heavier and bigger and never releasing the pent-up memory.

When adding interaction to your pages, does yourself (and the person maintaining your code on the future) a favor, and Caref Ully consider which element really needs to be listening.

Additional Articles Worth Reading
Nczonline.com–the Technical Blog of Nicholas zakas.http://www.nczonline.net/blog/2009/06/30/ event-delegation-in-javascript/

Explain how the works in JavaScript
The "This" keyword in JavaScript was a commonly used method to refer to the code's current context.

    • If "This" have not been set to anything then it defaults to the global object, which is usually Window.
    • If A function is running in an in-line function, such as an event listener and then "this" would refer to the source of th e function. For example if setting a click handler for a button, ' this ' would refer to the button inside the anonymous function.
    • If A function is a constructor for a object and then this would refer to the new object.
    • If A function is being defined in an object, and then when invoked on the object, ' this ' would refer to the object.

In a world of asynchronous programming and the helpful existence of promises, it's easy for ' this ' to ' change ' in the Cours E of one feature ' s operation. One trick to keep a handle in the context that started the operation are to set it to a variable inside a closure. When your call a function where context changes, like setTimeout, you'll still be able to reference the object you need t Hrough that variable.

The other one-to-one can manipulate "this" are through the use of call, apply, and bind. All three of these methods is used to invoke a function with a specific context of ' this '. Instead of relying on the browser operation-to-figure out what ' this ' is, you can tell the code to use the ' the object ' is Proposing. Call, apply, and bind can is pretty sophisticated in their own right and deserve their own writeup. We'll address them in a future installment. An example of the many changing ways of ' this ' is below:

 <  div  id  = "Appendhere"  ></ div  >  <  button  id  = "ClickMe"  >  Click Me</ >  
 var  div = $ (' #appendHere '  ' # ClickMe '). On (' click ', function   () { Span style= "color: #0000ff;"    >var  that = this  ;    Div.append (Checkforwindow ( this   function   () {Div.append (        Checkforwindow ( this   <strong>that</strong> is the ' + that.tagname + ' <br/> ' ); },  300 

Fiddle Code Explanation
When the button was initially clicked, the this value is an output to a div. Since Click operates from the button context, ' This ' is the button. Using SetTimeout causes the context to the Window. When ' This ' is called in the ' timeout function ' is, ' this ' reverts to the global context. You'll notice we set a variable called ' that ' which we set initially to the ' this ' context. When invoked in the SetTimeout, that's still refers to the original "this".

Event delegation and "This" is important features of modern JavaScript. Understanding how they work is critical to successful development, and almost certainly necessary to understand to get th At peach position of a JavaScript Engineer.

JavaScript Interview Questions:event delegation and this

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.