Communicate Unrelated Component Using Aura Component
We can communicate unrelated components using application event. Application events are handled by any component defined by the event.
Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified.
Each unrelated components are handle events except registerer component, the <aura:handler> element handles the event passed by the registerer component and the event attribute contain the event name which receives concern event (e.g.,: event=”c:nameofvent”)
Application Event:
<aura:event type="APPLICATION" description="Sample Application Event">
<aura:attribute name="message" type="String" />
</aura:event>
In application event the <aura:event> contain the attribute is type and its value should be APPLICATION, so the application type event support unrelated components communication. The <aura:attribute> tags type given as string and it support the string of values to be passed.
Register Event
Register event is normally pass/communicate with the event handling components
<aura:registerEvent name="SampleApplicationEvent" type="c:SampleApplicationEvent"/>
Here the type attribute contain the event name (i.e.: c:SampleApplicationEvent) via this event name the registerer component send the values.
Handle Event
<aura:handler event="c:SampleApplicationEvent" action="{!c.component2Event}"/>
The <aura:handler> tag contain the event and the action, event is the event received from the subscriber and then in the action process that received event.
Usecase
Pass the String value from registerer component to the handler component using application event.
For this example, we have to create the event and give its type as Application. And add the attribute element and that element type as String and chosen the name as message.
SampleApplicationEvent.evt
<aura:event type="Application" description="Sample Application Event">
<aura:attribute name="message" type="String" />
</aura:event>
Note: –
Here, the <aura:event> elements type is Application, then it is used for the application event method (i.e., publisher-subscriber pattern). And in that <aura:attribute> element contain the type as String so it will support to communicate the String type values between the Components.
Registerer Component
Component1.cmp
<aura:component implements=”force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId” access=”global” >
<aura:registerEvent name=”SampleApplicationEvent” type=”c:SampleApplicationEvent”/>
<lightning:card title =”Application Event communication “>
Event Register component
<lightning:button label=”Click to fire the event” variant=”brand” onclick=”{!c.component1Event}”/>
</lightning:card>
</aura:component>
Note: –
Here, in that component1 we use the <aura:registerEvent> element to register the event and its type we have mention the name of event to pass the string to that application event, then use the button to call the method to pass message to the handler component.
Component1Controller.js
({
component1Event : function(cmp, event,helper) {
//Get the event using event name.
var appEvent = $A.get(“e.c:SampleApplicationEvent”);
//Set event attribute value
appEvent.setParams({“message” : “Welcome “});
appEvent.fire();
}
})
Note: –
Here in this component when the “component1Event” method is initiated, then the value of “message” will be set to the application event, then the application event will fired here itself by fire() method.
HandlerComponent
Component2.cmp
<aura:component implements=”force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId” access=”global” >
<aura:attribute name=”eventMessage” type=”String”/>
<aura:handler event=”c:SampleApplicationEvent” action=”{!c.component2Event}”/>
<lightning:card title =”Application Event communication “>
Event Handler component
<div class=”slds-m-around_xx-large”>
<p>Handled event : {!v.eventMessage}</p>
</div>
</lightning:card>
</aura:component>
Note: –
Here, in this component use <aura:attribute> element, in that element use name attribute to store the received event and indicate the type as string. Then the <aura:handler> element contain the event attribute which indicate the name of event and the action is perform the receive event via the “component2Event” method.
Component2Controller.js
({
component2Event : function(cmp, event) {
//Get the event message attribute
var message = event.getParam(“message”);
//Set the handler attributes based on event data
cmp.set(“v.eventMessage”, message + ‘Jegadeesh’);
}
})
Note: –
Here, in this controller we get the event by using the method event.getParam() and finally we have to set the values to the “eventMessage” variable using set() method.
Scenario 2:-
For the following scenario I Create a new Account and pass that account to another component but both the components are not related to each other.
SampleApplicationEvent.evt
<aura:event type=”Application” description=”Sample Application Event”>
<aura:attribute name=”message” type=”Account[]” />
</aura:event>
public class CreateAccount {
//Insert Account from Aura by Apex Controller
@AuraEnabled
public static String createAcc(Account acc) {
insert acc;
System.debug(‘Id is :=> ‘ + String.ValueOf(acc.Id));
return String.ValueOf(acc.Id);
}
}
Component1.cmp
<aura:component controller=”CreateAccount” implements=”force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId” access=”global” >
<aura:registerEvent name=”SampleApplicationEvent” type=”c:SampleApplicationEvent”/>
<aura:attribute name=”AccountList” type=”Account[]” default=”{‘sobjectType’:’Account’,
‘Name’:”,
‘AccountNumber’:”,
‘Phone’:”,
‘Website’:”}”/>
<aura:attribute name=”accountId” type=”String”/>
<aura:attribute name=”AccountListEvents” type=”Account[]” />
<!–this handler to load the account’s when page loads/Renders–>
<lightning:card title=”Create Record”>
<lightning:input name=”accName” label=”Account Name ” value=”{!v.AccountList.Name}” />
<lightning:input name=”accNumber” label=”Account Number ” value=”{!v.AccountList.AccountNumber}” />
<lightning:input name=”accPhone” label=”Phone” value=”{!v.AccountList.Phone}” />
<lightning:input name=”accRating” label=”Website” value=”{!v.AccountList.Website}” />
<lightning:button variant=”brand” label=”Create Account” title=”Brand action” onclick=”{!c.CreateAccount }”/>
<br/>
<aura:if isTrue=”{!v.accountId}”>
Created AccountId : {!v.accountId}
<br/>
Click below to pass Account
<br/>
<lightning:button label=”Click to fire the event” variant=”brand” onclick=”{!c.component1Event}”/>
</aura:if>
</lightning:card>
</aura:component>
Component1Controller.js
({
//This function to create an account
CreateAccount : function(component, event, helper) {
//Calling server-side apex method
var action = component.get(‘c.createAcc’);
//Passing value to the apex method that accepts parameter.
//Here apex parameter is case-sensitive in js, how you have wrote in apex method same ,
//you have to write in here as well.
//check apex method paramter and acc below.
action.setParams({
“acc”: component.get(‘v.AccountList’)
});
action.setCallback(this, function(response) {
//store state of response
var state = response.getState();
var accId = response.getReturnValue();
component.set(“v.accountId” , accId);
console.log(‘AccountId’ + accId);
if (state === “SUCCESS” && accId != null) {
//No need to worry below code.
//This is the stadard code for toast message.
var toastEvent = $A.get(“e.force:showToast”);
toastEvent.setParams({
title: ‘Success!’,
message: ‘The record Created successfully.’+state,
duration:’ 5000′,
key: ‘info_alt’,
type: ‘success’,
mode: ‘pester’
});
toastEvent.fire();
}
else if(state === “ERROR”) {
var toastEvent = $A.get(“e.force:showToast”);
toastEvent.setParams({
title : ‘Error’,
message:’This is an error message’+state,
duration:’ 5000′,
key: ‘info_alt’,
type: ‘error’,
mode: ‘pester’
});
toastEvent.fire();
}
else if(state === “WARNING” ){
var toastEvent = $A.get(“e.force:showToast”);
toastEvent.setParams({
title : ‘Warning’,
message: ‘This is a warning message.’+state,
duration:’ 5000′,
key: ‘info_alt’,
type: ‘warning’,
mode: ‘sticky’
});
toastEvent.fire();
}
else if(accId == null){
var toastEvent = $A.get(“e.force:showToast”);
toastEvent.setParams({
title : ‘Warning’,
message: ‘Required Field Missing.’,
duration:’ 5000′,
key: ‘info_alt’,
type: ‘warning’,
mode: ‘sticky’
});
toastEvent.fire();
}
});
$A.enqueueAction(action);
},
//This method register the Event
component1Event : function(cmp, event,helper) {
//var accId = component.find(“accountId”).get(“v.value”);
var accName = cmp.get(“v.AccountList”);
var accId = cmp.get(“v.accountId”);
accName.Id=accId;
console.log(‘Publishing Component’);
console.log(‘AccountList’+JSON.stringify(accName));
//Get the event using event name.
var appEvent = $A.get(“e.c:SampleApplicationEvent”);
//Set event attribute value
appEvent.setParams({“message” : accName});
appEvent.fire();
}
})
Component2.cmp
<aura:component implements=”force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId” access=”global” >
<aura:attribute name=”eventMessage” type=”String”/>
<aura:handler event=”c:SampleApplicationEvent” action=”{!c.component2Event}”/>
<lightning:card title =”Application Event communication “>
Waiting For Account to Receive
<aura:if isTrue=”{!v.eventMessage}”>
<div class=”slds-m-around_xx-large”>
Handled :<p style=”color:#ed1f41″> {!v.eventMessage.sobjectType}</p> <br/>
Record Id : {!v.eventMessage.Id}<br/>
Account Name : {!v.eventMessage.Name}<br/>
Account Number : {!v.eventMessage.AccountNumber}<br/>
Phone No. : {!v.eventMessage.Phone}<br/>
Account Site : {!v.eventMessage.Website}<br/>
</div>
</aura:if>
</lightning:card>
</aura:component>
Component2Controller.js
({
component2Event : function(cmp, event) {
//Get the event message attribute
var message = event.getParam(“message”);
//Set the handler attributes based on event data
console.log(‘Handling Component’);
console.log(‘message’+JSON.stringify(message));
cmp.set(“v.eventMessage”, message);
}
})
After account is created look like
After fire the event by Registerer component