This blog will be focusing on two event types provide by Salesforce. One is Application Events and another is component Events and how we can pass values from one component to another.
Application Events
When you want to pass values between two independent component at that time we will use Application Events. Lets say you have two independent, say SENDER component which takes Name as input from the user and passes its value to say RECEIVER component.
Steps to create Application Event:
1. Create a Event with type as APPLICATION
<aura:event type="APPLICATION" description="Description for Event">
<aura:attribute name="param" type="Object" description="Description for parameter"/>
</aura:event>
2. Register event in SENDER component
<aura:registerEvent name="senderEvent" type="c:EventName">
<aura:attribute type="String" name="firstname" />
<lightning:input type="text" name="firstname" value="{!v.firstname}" /><button onclick="{!c.callEvent">Send</button>
JS controller
({
callEvent : function(cmp, event, helper) {
var e = $A.get("e.c:EventName"); // get Event
e.setParams({ "param" : cmp.get("v.firstname")}; //set param value for event
e,fire(); // fire event
}
})
3. Now Handle event in RECEIVER component by adding handler for event<aura:handler event="c:EventName" action="{!c.receiveParam}" /> //hadler to handler event
JS controller
({
receiveParam : function(cmp, event, helper) {
var param = event.getParam("param"); //get param value
console.log("Value recieved from SENDER component is: " + param);
}
})
Every component which has Handler can receive param value send by SENDER component for APPLICATION type event.
Component Event
Lets say you want pass value between child to parent in this case you can use component event. Here sender will be child component and reciever will be parent component.
Steps for it.
1. Create event of type COMPONENT
<aura:event type="COMPONENT" description="Description for Event">
<aura:attribute name="param" type="Object" description="Description for parameter"/>
</aura:event>
2. Register event in SENDER component same as in Step 2 of Application Event
attribute name for aura:registerEvent should be same in aura:handler name attribute.
here: name="senderEvent"
<aura:registerEvent name="senderEvent" type="c:EventName">
<aura:attribute type="String" name="firstname" />
<lightning:input type="text" name="firstname" value="{!v.firstname}" />
<button onclick="{!c.callEvent">Send</button>
JS controller
({
callEvent : function(cmp, event, helper) {
var e = $A.get("e.c:EventName"); // get Event
e.setParams({ "param" : cmp.get("v.firstname")}; //set param value for event
e,fire(); // fire event
}
})
3. Add handler with name="senderEvent"
<aura:handler name="senderEvent" event="c:EventName" action="{!c.receiveParam}" />
//handler to handle event
It's mandatory in Component event to set name attribute in event registration and handler, as param can be exchange in parent child component only.
Hope you like the post! Enjoy Coding.