Component Events in Lightning


This blog will be explaining how to use component event in lightning component by implementing simple search application for Accounts.
There are two types of events
  1. Component Event :
Component event can be handled by any component which is above event firing component in the containment hierarchy.
It is best practice to always try to use component event, if possible. Component events can only be handled by components above them in the containment hierarchy so their usage is more localized to the components that need to know about them.
  1. Application Event :
Application event can be handled by any component where handler is provided. Application event is used where components are different parts of application and there is no containment hierarchy.
Lets implement simple searching application with two components and communicate between components by a component event. We have following components and events.
1) eventAccount (event):
This is a component event having attribute accountList of type List of Account.
2) searchBox (component):
This is a component having an input text box and a button. This component registers an event of type eventAccount with name “searchEvent”. After clicking button, Its handler (handleClick) invokes controller action (getSearchedAccount) and sets the list of Accounts returned to accountList attribute of searchEvent and fires the event.
3) displayList (Component):
This is a container component of searchBox. It has markup to display accounts and an event handler (eventHandler) to handle searchEvent fired by searchBox component, this eventHandler sets attribute of handled event (accountList) to the attribute of displayList component(accounList).

Code

eventAccount(Event)
appEvent<aura:event type="COMPONENT" description="Event template" >
    <aura:attribute name="accountList" type="Account[]">
    </aura:attribute>
</aura:event>

searchBox.cmp (Component)
<aura:component controller="lightningSearchController" >
    <aura:registerEvent name="searchEvent" type="c:eventAccount"/>
    <aura:attribute name="nothingFound" type="String"/>
    <ui:inputText aura:id="searchBoxId" label="Search for" required="true"/>
    <ui:button aura:id="searchButton" label="Search" press="{! c.handleClick }" />
    <br/>
    {!v.nothingFound}
</aura:component>

searchBoxController.js (Component Controller)
({
 handleClick : function(component, event, helper) {
        //get value in searchBox
  var searchTerm = component.find("searchBoxId").get("v.value");
        //create a one-time use instance of the getSearchedAccount action and set parameters.
        var action = component.get("c.getSearchedAccount");
        action.setParams({searchTerm : component.find("searchBoxId").get("v.value")});
        action.setCallback(this, function(res){
            var state = res.getState();
            if(state == "SUCCESS")
            {
                var searchEvent = component.getEvent("searchEvent");
                //If no data found
                if(res.getReturnValue() == '')
                {
                  component.set("v.nothingFound", "No data found");
                }
                // set data returned by server side action to eventAccount
                searchEvent.setParams({ "accountList" : res.getReturnValue() });
     searchEvent.fire();
            }
        }
        );
        $A.enqueueAction(action);
 }
})

displayList.cmp (Component)
<aura:component >
    <aura:handler name="searchEvent" event="c:eventAccount" action="{!c.eventHandler}"/>
    <ltng:require styles="{! $Resource.SLDS105 + '/assets/styles/salesforce-lightning-design-system.css'}"/>
    <aura:attribute name="accountList" type="Account[]"/>
    <c:searchBox />
   <table  class="slds-table slds-table--bordered slds-table--striped">
    <aura:iteration items="{!v.accountList}" var="acc">
         <tr>
                                 <td>{!acc.AccountNumber}</td>
                                 <td>{!acc.Name}</td>
                                 <td>{!acc.Industry}</td>
                                 <td>{!acc.Type}</td>
                            </tr>
    </aura:iteration>
    </table>
</aura:component>

displayListController.js (Component Controller)
({
 eventHandler : function(component, event, helper) {
        var message = event.getParam("accountList");
      // set the handler attributes based on event data
        component.set("v.accountList", message);       
 }
})

searchApp (Application)
<aura:application > 
    <c:displayList />
</aura:application>

lightningSearchController.apxc (Apex class)

public class lightningSearchController {
    @AuraEnabled
    public static List<Account> getSearchedAccount(String searchTerm)
    {
        List<Account> accList = (List<Account>)([FIND :searchTerm
            IN ALL Fields
            RETURNING Account(Id, Name, AccountNumber, Industry, type, Phone )].get(0));
        System.debug('accList'+accList);
        return accList;   
    } 
}


There are many Accounts of 'Amit' in my org. lets search for it and results of search are  below.

Comments

  1. Failed to save undefined: No EVENT named markup://c:eventAccount found : [markup://c:searchBox]: Source

    ReplyDelete
  2. Create component event "eventAccount". I have updated blog.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

Uploading multiple files as attachments using chaining of actionfunction in single click.

Dynamic Visualforce Bindings with Example

Two Columns Multi-Select Picklist Lightning Component