Capturing browser events

The life cycle of an event consists of the capture, target, and bubble phases. The following diagrams show the direction of an event flow for the capture and bubble phases.

The following diagram shows the direction of an event flow during its capturing phase. Observe that the event flows from a parent node to its child node:

  

The following diagram shows the direction of an event flow during its bubble phase. During the bubble phase, the events flow from the child node to the parent node:

Let's create a Lightning Application bundle using the Developer Console (or SFDX project) set up, to help us understand a browser event in a JavaScript application:

<aura:application >
<div onclick="{!c.handleClick}" id="divId">
<em>If you click on <code>EM</code>, the handler on <code>DIV</code> runs.</em>
</div>
</aura:application>

The JavaScript controller is as follows:

({
handleClick : function(component, event, helper) {
console.log(event.target.innerHTML);
console.log(event.currentTarget.innerHTML);
var divElement = document.getElementById('divId');
divElement.addEventListener('click', helper.helperMethod(component, event), false);
}
})

The helper class code is as follows:

({
helperMethod : function(component, event) {
console.log('hello');
}
})

When you click the EM in the browser, the console logs are as follows:

From the preceding content, we can infer the following things about HTML elements in Lightning Components:

  • event.target gets the proxy object of the object that dispatched the event
  • event.target gets the deepest element that originated the event
  • event.currentTarget identifies the element that was bound to the event
  • You can add an event listener to the HTML DOM elements, to listen for both the capturing and bubble phases

If you need a visual explanation of the differences between the target and currentTarget, refer to http://joequery.me/code/event-target-vs-event-currenttarget-30-seconds/.

The event listener, addEventListener, has a third parameter as a Boolean, to indicate whether you need to capture the event during its bubble phase or capture phase. True indicates that it's the capture phase, and we rarely use them in real applications.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.127.37