How to Communicate Between two Lightning Components using Events?
Event:
An event can be something the browser does or something a user does.
Lightning framework uses event-driven programming. Handlers are written for interface events and they handle the events as they fire. In Lightning, framework events are triggered by client-side JavaScript controller actions. The attributes in an event could be set before the event gets triggered and read-only when the event is handled.
In Lightning framework events are declared by the aura:event tag in a .evt resource. Events can be of two types :
- Component Events: A component event can be triggered by an instance of a component and can be handled by the component that triggered it or by any other component in the hierarchy that receives the event.
- Application Events: An application event is fired by an instance of a component and all the components that provide a handler for the event are notified.
Steps to communicate between two Lightning Components using events:
- Create an event.
- Create two lightning components: Child component and parent component.
- Register the event in the child component and fired the event in the child component JavaScript controller action.
- Handle the event in the parent component.
A snippet of code for the lightning Event:
<aura:event type="COMPONENT"> <aura:attribute name="message" type="String" default="“”/"></aura:attribute> <!-- attribute of event --> </aura:event>
A snippet of code for the child component:
<aura:component> <aura:registerevent name="componentEventFired" type="c:CustomEvent"></aura:registerevent> <!-- Event is being register in child component--> <ui:button label="EventFire" press="{!c.fireComponentEvent}"></ui:button> <!-- Event will fired on click of this button --> </aura:component>
A snippet of code for the child component JavaScript controller:
({ fireComponentEvent : function(cmp, event, helper) { var compEvents = cmp.getEvent("componentEventFired");// getting the Instance of event compEvents.setParams({ "message" : "Child Event Fired" });// setting the attribute of event compEvents.fire();// firing the event. } })
A snippet of code for the parent component:
<aura:component controller="AccountLight"> <aura:handler name="componentEventFired" event="c:CustomEvent" action="{!c.handleEvent}"></aura:handler> <!-- Handler for custom event --> <aura:attribute name="ParentAttribute" type="String" default="”"></aura:attribute> <!-- Attribute of parent component --> The ValueOf Attribute is {!v.ParentAttribute} </aura:component>
A snippet of code for parent component Javascript controller:
({ handleEvent : function(component, event, helper) { var name =event.getParam("message");// getting the value of event attribute console.log('name:::'+JSON.stringify(name)); component.set("v.ParentAttribute",name); // Setting the value of parent attribute with event attribute value } })