Handling Custom Events in the Lightning Component Framework

Learn about the mechanisms provided for working with custom events in the Lightning Component Framework.

Guest post: Peter Knolle is a Solutions Architect at Trifecta Technologies, Force.com MVP, and Salesforce Developer Group Organizer.  He holds six Salesforce certifications, blogs regularly at peterknolle.com, and is active on Twitter @PeterKnolle.

The Lightning Component Framework uses an event-driven architecture and provides an infrastructure for developers to create their own custom Lightning events. Event-driven programming is a programming paradigm that allows developers to write functions to respond to fired events. The framework waits for events to be generated from user interactions such as button clicks and mouse overs, or by non-interactive actions such as loading completions or component renderings. When an event is fired the function(s) that have been declared to handle it are called by the framework. This post describes the mechanisms provided for working with custom events in the Lightning Component Framework.

By the way, I should mention that the Lightning Components module in Trailhead is the best to get started while earning badges to demonstrate your skills. And be sure to check out all of the resources on the Lightning Components page at Salesforce Developers.

Using Custom Events

Consider an application that allows users to search for Contacts and displays the results as a table of Contacts.

screenshot of contacts app

You might be thinking that is simple…create a text input, a button, a table of results, perform the search, and display the results. Nothing to it! The better approach with component-based, event-driven programming is to separate out the search piece into its own component distinct from the table of results and have the search component fire an event when its search has completed. The benefit of this is that the search component can then be paired with other components that use its results differently. But it’s not just the search component that can be reused. The table component can be reused in other contexts as well.

Events in the Lightning Component Framework are either component level or application level. Let’s explore the Contact application, and the contactSearch and contactTable components it uses to see how a component-level or application-level event can be used.

Component-Level Events

Component-level events are generated by a component and can be handled by the component itself, or its containing component or application. Component events are useful for situations where your component can be used in an application multiple times and you don’t want the different instances interfering with each other. So, if the intent of the contactSearch was that it could be used in the application more than once, it would make sense for it to generate a component-level event. Let’s look at how that is done.

Create a Lightning Event

A Lightning Event must be created and the type attribute must be specified as “COMPONENT.” The name that you specify is the event’s type and is displayed as the name of the file, e.g., contactSearchCompleteEvent. Note that the event type is specified in business terms and not in lower-level or implementation-level terms (e.g., serverCallDone, jsonReady, apexComplete, etc.). It is better to not let the lower-level details be part of the event’s specification.

<aura:event type="COMPONENT" description="Fired when a Contact search is completed">
    <aura:attribute name="contacts" type="Contact[]" description="The result of the search, which could be an empty array"/>
</aura:event>

The aura:attribute defines the data that can be carried with the event. It is also referred to as the event’s shape.

Register the Event

The contactSearch component registers that it can generate the event with the aura:registerEvent component.

<aura:component controller="ContactSearchController">
    <aura:registerEvent name="contactSearchComplete" type="c:contactSearchCompleteEvent"/>

    <div class="searchInput">
    	<ui:inputText label="Term" aura:id="searchTerm" value="" placeholder="Enter term" />
    </div>
    <ui:button label="Search" press="{!c.doSearch}" class="action-button" />
</aura:component>

The aura:registerEvent specifies the event type. Note the “c:” prefix. That is the default namespace and is used in orgs that do not have a namespace. The name attribute is what the component’s container uses to specify which of its controller functions should be called when the event is fired.

Declare the Handler

In the Contact application, the app’s handleContactSearchComplete controller method will be called when the event is fired.

<aura:application >
    <aura:attribute name="appContacts" type="Contact[]"/>
     <div class="app">
        <c:contactSearch contactSearchComplete="{!c.handleContactSearchComplete}"/>
        <div class="table">
            <c:contactTable aura:id="contactList" contacts="{!v.appContacts}"/>
        </div>
    </div>
</aura:application>

Fire the Event

The contactSearch component creates the event, sets its parameters, and fires it after the search has completed. This code resides in a helper function that is called from a controller function.

var searchCompleteEvent = component.getEvent("contactSearchComplete");

searchCompleteEvent.setParams({
    contacts: contacts
}).fire();

Handle the Event

The app’s handler method is then called, which allows it to update its list of Contacts.

handleContactSearchComplete : function(component, event, helper) {
    component.set("v.appContacts", event.getParam("contacts"));
}

The parameter that was set is retrieved with the getParam method. Note another extremely powerful aspect of the Lightning Component Framework at work here. There is no need to write code to manipulate the DOM to update the table. A single line of code to set the attribute value that the table uses will automatically update the table.

Application-Level Events

Application-level events are published by a component, and any component or application that has subscribed to the event has its handler invoked when the event is fired. If the design of the contactSearch was that it should only be used once in an application and multiple components need to respond to process its results, it would make sense to use an application-level event. There are some slight modifications that can be made to the component-level, event-related code to convert it to an application-level event code.

Create a Lightning Event

The only thing that changes in the Lightning Event is the level=”COMPONENT” changes to level=”APPLICATION.”

Register the Event

Nothing needs to change with the way the component uses the aura:register to declare that it fires the event.

Declare the Handler

The app’s markup changes to not specify an event handler on the component anymore, but instead specifies that it handles the event type, with the aura:handler component.

<aura:handler event="c:contactSearchCompleteAppEvent" action="{!c.handleContactSearchComplete}"/>

Fire the Event

The only thing that changes in the event firing code is to get the event in a different way. Instead of component.getEvent(), an Aura framework method is used to get the event:
$A.getEvt(“c:contactSearchCompleteAppEvent”).

Handle the Event

The handler, handleContactSearchComplete, does not need to change.

More

For more information on event handling in the Lightning Component Framework, refer to the Lightning Component Developer’s Guide. For a quick overview and introduction to Lightning Components, visit the Lightning Components page on Salesforce Developers. If you’re ready to learn hands-on while earning badges to demonstrate your skills, start the Lightning Components module in Trailhead.

Published
March 10, 2015

Leave your comments...

Handling Custom Events in the Lightning Component Framework