Posts tagged ‘DOM’

Handle DOM Events Raised by Base Lightning Components

Buntysmum / Pixabay

Base Lightning components, introduced with the Winter ’17 release, provide developers with granular and reusable “out of the box” components that can be used to render HTML for everything from navigation menus, to form fields, to data tables, and many other UI patterns in between.

The primary value add of base Lightning components is that they apply the Salesforce Lightning Design System (SLDS) styling to the HTML that is output when the components render.

Another value add is that many of the base Lightning components raise events that can be handled within your component hierarchy.

By now you should realize that the Lightning Component Framework is an event driven architecture, and how you manage events is a critical aspect to Lightning application design.

Thankfully, raising and handling events from base Lightning components is in itself fairly straightforward and handles many of the use cases requiring events to be raised from user interaction.

What I have found in my own development experience is that there are certain edge use cases where the events raised by base Lightning components do not go far enough.

This doesn’t mean we need to throw the baby out with the bathwater and abandon base Lightning components in favor of hand writing all custom HTML and JavaScript, however.

It just takes a deeper understanding of how events are raised and handled to find an elegant solution that incorporates base Lightning components and a minimal amount of custom HTML.

I would like to propose a simple solution for when you run into situations where you need a more robust set of events than what are raised by base Lightning components, and provide some background on “how” and “why” this works.

A Common Pattern: Onfocus and Onblur

One of the things that I have noticed with the architecture of base Lightning Components is that many of them share a common pattern in the way in which they raise events.

While some base Lightning components do not raise any events of their own, many components in the lightning: namespace have event attributes that can be used to raise and handle events within the component hierarchy.

Of the base components that do raise events, such as <lightning:input>, <lightning:select>, <lightning:button> and others, share the same two component event attributes: onfocus and onblur.

The focus event is raised when an element is in focus – meaning a user has clicked on or tabbed to that particular element.

blur is the opposite of focus. When an element is currently in focus and the user then clicks on or tabs to a new element, the blur event fires on the previously focused element while the focus event fires on the newly focused element.

The focus and blur events are typically associated with HTML elements such as <select>, <input> and <a>, but it is important to note that the onfocus and onblur event attributes for base Lightning components do not raise the focus or blur Document Object Model (DOM) events.

When a base Lightning component includes the onfocus or onblur event attributes in its definition, what it actually raises is an event that is custom to the Lightning Component Framework and can only be handled by another Lightning component.

Beyond Blur: Additional Base Lightning Component Event Attributes

Most of the components that raise the focus and blur events will also raise another complementary event specific to the way in which a user interacts with the component itself.

For example, in addition to the onfocus and onblur event attributes, <lightning:button> can raise a third event called click by including the onclick event attribute with a reference to a controller function.

This is because the expected interaction with the <lightning:button> component is for a user to click on it.

The <lighting:select> component, which displays a picklist of options, raises a third event called change by including the onchange event attribute in the reference to the component.

Again, this is because the expected interaction with <lightning:select> is for a user to select an option from a dropdown list, and if the newly selected value is different from the previously selected value, that may be of significance from a UX perspective and require the firing of an event.

Remember, when base Lightning components fire events, they are not DOM events – they are component events raised by the Lightning Component Framework.

While they may not be DOM events, they follow a similar propagation pattern in that the events “bubble up” through the component hierarchy and can be handled by any component in the ancestry starting from the component that fired the event all the way up to the root (top level) component. We’ll cover the concept of bubbling a little later to understand how all of this works.

The reason why it is great that Salesforce provides these event attributes for base Lightning components is because the focus and blur DOM events do not bubble and must be handled by event listeners defined at the level of the specific HTML element that raises the event.

In contrast, using the onfocus and onblur Lightning component events enable the events to be handled by a parent Lightning component that references a JavaScript function in its local controller.

These component events are powerful and handle most use cases for firing events directly from base Lightning components based on specific user interactions, but how does it work if you want to handle events other than focus, blur, change or click?

Base Lightning Components and DOM Events

What happens when you want to handle DOM events such as keyup or mouseover from a <lightning:input> component? How can you handle the dblclick event for a <lightning:formattedText> component?

Well…in a nutshell, you can’t. Why? Because there are no attributes defined for these events in base Lightning components.

Lightning components only support events explicitly listed in the documentation. If <lightning:input> only lists onfocus, onblur and onchange as event attributes, then those are the only events that it raises and can be handled by the parent component.

Not to worry, though. There is a solution if you want to handle DOM events that are not explicitly supported by base Lightning component event attributes.

Handling DOM Events Raised by Base Lightning Components

To handle an event that is not supported for a given base Lightning component, you simply need wrap the component in a containing HTML element. This will typically be a <div>, and you will handle the DOM event there.

For example, if you want to handle the dblclick event when a user double clicks the mouse on a <lightning:formattedText> component, simply wrap it in a <div> and include the ondblclick event attribute in the reference to the containing <div> as illustrated:



<div ondblclick=“{!c.myDblclickEventHandler}”>
    <lightning:formattedText value=“Double click on me!“ />
</div>


Why does this work?

To understand why this works, you first have to understand something called “bubbling.”

The concept of bubbling is fairly straightforward. When an event that supports bubbling is fired from an HTML element, that event can be first be handled by the actual element raising the event if it has a handler defined for the event.

Note: Not all events support bubbling. As mentioned previously, the focus and blur events do not bubble.

If the HTML element raising the event has not added a listener for the event, or if it does handle the event but does not explicitly stop bubbling by referencing the stopPropagation() function on the Event object, the event will bubble to the parent element of the element that raised the event.

Following the same pattern, the event will continue to raise its way through the DOM tree starting with the parent HTML element and continuing until bubbling is explicitly stopped or the event reaches the root of the HTML document without being handled.

How Does DOM Event Propagation Apply to Base Lightning Components?

Earlier we mentioned that base Lightning components do not support the raising of DOM events, only component events that are raised and handled within the Lightning Component Framework itself.

So what does DOM event bubbling have to do with base Lightning components?

The answer is simple if you think about what base Lightning components actually do – base components exist to simplify the process of generating HTML for UI elements that implement SLDS for you automatically.

Rather than having to hand write all of the HTML and CSS to implement SLDS prototype components such as buttons or form input fields, base Lightning components allow developers to control the styling and behavior of the rendered output by setting attribute values in the definition of the base component.

Base Lightning components, in turn, render HTML elements with references to CSS classes defined in the SLDS external stylesheet.

For example, the following reference to a base Lightning component:

<lightning:input name="mySampleComponent" label="This is a sample lightning:input component" />

Renders the following markup:


<div class="slds-form-element lightningInput" data-aura-rendered-by="5:0" data-aura-class="lightningInput">

    <label class="slds-form-element__label slds-no-flex" for="3:0" data-aura-rendered-by="7:0">

        <span class="" data-aura-rendered-by="9:0">

        This is a sample lightning:input component

        </span>

    </label>

    
<div class="slds-form-element__control slds-grow" data-aura-rendered-by="11:0">

        <input class="slds-input" type="text" id="3:0" style="" data-aura-rendered-by="12:0" name="mySampleComponent">

    </div>


</div>

To break this down, at the core of the rendered output we have an HTML <input> element that is contained by a <div> element. We also have a <span> element, which is the child of a <label> element.

The containing <div> element for the <input> as well as the <label> element are themselves wrapped by a top-level containing <div>.

That’s a lot of nesting! This complex output is simplified by the use of the <lightning:input> component, but how does this apply to raising and handling DOM events?

How Does This Work?

Let’s say that we want to handle the focus event for the <lightning:input> base Lightning component in the previous example. This would be simple because <lightning:input> has an event attribute called onfocus.

All we would need to do in order to handle focus is include the onfocus attribute and reference a controller function like this:

<lightning:input onfocus=“{!c.myFocusEventHandler}” />

Because focus is a component event, we could get information about the component that raised the event by using the getSource() method on the Event object in our controller function:

myFocusEventHandler : function(component, event, helper) {

    var sourceComponent = event.getSource();

    // Additional logic

}

Simple enough, right?

So now let’s say we wanted to handle the keyup event that gets raised from the <input> element when a user presses and releases a key on the keyboard.

When this event is raised we want to call a function to check whether the user pressed the “tab” or “enter” keys.

How do we do that since onkeyup is not listed as an event attribute in the documentation for <lightning:input>?

This is where we want to wrap our base Lightning component with an HTML element such as a <div> and have the containing element handle the event.

Remember, most DOM events support bubbling. In this example, the keyup event will be raised by the HTML <input> element generated by the <lightning:input> component when it is rendered.

The keyup event will not be handled by the <input> element itself, nor will it be handled by the <div> that contains it or the top-level <div> rendered by the component.

It will bubble up to our wrapper <div> and we will handle the keyup event there by calling the controller function referenced in the onkeyup event attribute.

Here’s what this would look like in your custom component markup:


<div onkeyup=“{!c.myKeyupEventHandler}”>

    <lightning:input name="mySampleComponent" label="This is a sample lightning:input component" />

</div>

Handling the DOM Event

When we handle raised events that are native to the Lightning Component Framework, we get access to more robust event handling functionality, such as getting access to the component that raised the event by using event.getSource().

Unfortunately when we raise and handle DOM events like we are doing here, referencing event.getSource() will return an ‘undefined’ value.

So how do we get information about the raised DOM event? This is where we have to know a little bit of JavaScript.

When we raise and handle DOM events using JavaScript, we get access to a number of properties on the Event object that provide references to the HTML elements involved in the firing and handling of the events:

event.target references the HTML element that actually fired the event. In our use case, event.target will reference the <input> element where the keyup event occurred.

event.currentTarget references the HTML element that is currently handling the fired event. In our use case, event.currentTarget will reference the <div> that we used to wrap the <lightning:input> component.

Additional Considerations for Using event.target and event.currentTarget

Learning how to use event.target and event.currentTarget for DOM events and event.getSource() for component events will enable you to design a robust event-driven architecture in your custom Lightning components.

So why not just use event.target and event.currentTarget to handle all events, including DOM events and Lightning component or application events?

You can thank Locker Service for throwing cold water on that idea. event.target and event.currentTarget are not available when handling Lightning component events because of Locker Service restrictions.

Without going into the gory details, Locker Service wraps each Lightning component in a secure document that renders the HTML for that component within a virtual DOM.

Using event.target or event.currentTarget would essentially allow you to reach into the DOM for the source component, breaking encapsulation.

Also note that event.target and event.currentTarget are properties of the Event object – not methods. As such, you do not need to append () to the property name – if you do you will experience a JavaScript error.

Additional Resources