Posts tagged ‘Lightning Component Framework’

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

Understanding Lightning Component Framework Architecture

Traditionally, Salesforce UI design came down to two questions: Do I want to recreate the look-and-feel of Salesforce with custom Visualforce pages, or do I want to install a third party framework to create rich application interfaces?

The prevailing design pattern since the fall of Adobe Flash has been to use Visualforce to simply render the output from JavaScript frameworks such as Backbone, Angular, Ember, Sencha, and others. Developers could continue to follow MVC patterns by using Apex controllers to retrieve data from the Salesforce database.

While this may have enabled a rich, responsive experience for certain applications developed for Salesforce, users still had to deal with a mixed experience across all of Salesforce, especially if multiple JavaScript frameworks were in use.

Lighting Experience and the Lightning Component Framework solve a problem that has long been a barrier to a truly unified experience for all Salesforce users: Providing a single, integrated framework for developers that enabled the creation of rich, responsive applications that could be seamlessly “plugged in” anywhere in the UI rather than having to stand alone in separate pages or standalone applications.

Because the Lightning Component Framework is what underlies Lightning Experience and the Salesforce1 mobile applications, we no longer have to choose a JavaScript framework developed and maintained outside of Salesforce. We can now create components and applications using a rich JavaScript framework that is provided and maintained by Salesforce.

What is the Lightning Component Framework?

The Lightning Component Framework is a client-side UI framework that was built by Salesforce using the open source Aura UI framework. The framework uses JavaScript for client-side operations and exposes an API to access Salesforce data using Apex controllers.

The Lightning Component Framework was initially created to support development for the Salesforce1 mobile application, but is now the standard for responsive, client-side single page applications for the end-to-end Salesforce user and developer experience across all browsers and devices.

The framework provides a number of reusable out-of-the-box components for you to get started building your own Lightning Components, and the platform is fully maintained and supported by Salesforce.

The problem Salesforce solved with the Lightning Component Framework was to give Salesforce developers a single, standardized and supported JavaScript framework to move beyond the limitations of Visualforce and build rich applications with a common design system without having to select, install and maintain a third party framework.

Eliminating the JavaScript framework sprawl within the Salesforce development ecosystem enables developers and admins to deliver customized business solutions with a standardized look and feel without having to learn and maintain yet another framework from another vendor that wasn’t built specifically for the Salesforce platform.

What is JavaScript?

Along with HTML and CSS, JavaScript is one of the three core languages of web development.

If you do not have a background in JavaScript, don’t worry. Even though it will be the most difficult thing you will have to learn when coming up to speed on Lightning Component development, JavaScript has been around for decades and there are countless resources available for learning the language.

JavaScript was introduced in the mid-1990’s as a scripting language for the Netscape Navigator browser, with Microsoft subsequently releasing a version for Internet Explorer. By the late 1990’s, JavaScript was standardized across browsers with the introduction of what is called ECMAScript. Today, all modern browsers include JavaScript engines.

JavaScript will not be completely foreign to Apex developers or anyone with an object-oriented programming (OOP) background as it follows object-oriented principles. What will throw you off if you have an Apex background is the fact that JavaScript is loosely typed, whereas Apex is a strongly typed language. This will take some getting used to conceptually.

At its core, JavaScript is a language that is used to read and manipulate what we call the Document Object Model (DOM). The DOM is a programmatic interface that gets built when a browser reads an HTML document and converts each HTML element into what are called node objects. These HTML nodes form a tree-like structure in the DOM, and we can use JavaScript to find nodes, add nodes, remove nodes and modify nodes to make our web applications dynamic.

The other core function that JavaScript performs is listening for and handling events that occur in the browser. HTML itself is a static markup language and was not built to be dynamic in its rendering, which is why JavaScript was created to handle events such as clicking a mouse, changing a picklist value, or putting a form element into focus. You can write JavaScript functions to handle DOM events, and your JavaScript functions can in turn manipulate the DOM by adding, removing or modifying DOM elements.

Many of us have only had to learn JavaScript at a cursory level because JavaScript libraries like jQuery and JavaScript frameworks such as Sencha ExtJS, Angular, Node and Backbone take care of a lot of the heavy lifting for us when it comes to actual JavaScript programming.

Lightning requires more direct JavaScript programming than many frameworks do, which gives you greater control over the functions in your Lightning Components and Applications, but unfortunately you’re going to have to bone up on your JavaScript knowledge before you can take advantage of that level of control.

What are JavaScript Frameworks?

JavaScript frameworks handle much of the behind-the-scenes complexity of JavaScript coding and DOM manipulation, and give developers a simplified template-based approach to building web applications.

While JavaScript itself does not follow the Model View Controller (MVC) design pattern, many JavaScript frameworks implement MVC to provide developers with a familiar architecture for separating the data model and view of an application with a logic, or controller layer. Each component of the MVC architecture can be maintained separately and be brought together in a cohesive application.

Some frameworks, such as Sencha ExtJS, may implement MVC but are more focused on enabling rich user interfaces by giving developers pre-built UI widgets that can be configured declaratively. Other frameworks are designed for touch-driven responsive mobile applications. There are dozens of JavaScript frameworks out there, the most common examples being Backbone.js, AngularJS, Ember.js, Knockout.js, React.js and ExtJS among others.

What is Aura?

Aura is an open source JavaScript UI framework that is maintained by Salesforce. Aura is component-based, and uses JavaScript on the client-side front-end, with Java on the sever-side back-end. Aura is the framework that underpins the Lightning Component Framework.

While the Lightning Component Framework and Aura have many similarities on the surface, do not try to use Aura components or functions that are not explicitly supported in the Lightning Component Framework documentation. Many developers have already found that these undocumented features may work at first, but unless they are explicitly supported by Salesforce, they can be taken away at any time.