Activity › Forums › Salesforce® Discussions › How can we subscribe to an event in Salesforce Lightning Component?
Tagged: Attributes, Child Component, Events in Salesforce, Parent Component, Salesforce Lightning Component, Subscriber
-
How can we subscribe to an event in Salesforce Lightning Component?
Posted by Aman on September 23, 2018 at 11:05 PMHow can we subscribe to an event in Salesforce Lightning Component?
Parul replied 7 years, 7 months ago 3 Members · 2 Replies -
2 Replies
-
To subscribe to an event in lightning component we need to include tag in the containment hierarchy. Subscription of these event depends on the event type i.e. component event or application event. For Component event we write below code.
In this ‘name’ attribute in should be exactly as name attribute in tag in the component which has fired the component. The ‘action’ attribute of sets the client-side controller action to handle the event. The ‘event’ attribute specifies the event being handled.
For Handling Application event we write below code‘Event’ and ‘action’ attribute are same as the component event handling, it is just that we do not include ‘name’ attribute to handle the application event.
- [adinserter block='9']
-
In order to use Application event we need to follow the Four simple steps
- Create Application Event
- Fire the event from the child component
- handle the event into Parent Component
- Execute the action into Parent Component
Step 1 – Create Application Event
Open developer console and then File -> New -> Lightning Event -> name it applicationEvent and use below code.
<aura:event type=”APPLICATION” description=”Event template” >
<aura:attribute name=”testWord” type=”String” />
</aura:event>Step 2 – Register the event
Unlike the Component we do not need to register the Application Event.
Step 3 – Fire the component Event
Use below code in javascript to execute the event.
({
handleClick : function(component, event, helper) {
var appEvent = $A.get(‘e.c:applicationEvent’);
appEvent.setParams({
“testWord” : ‘Value From Application Event’
});
appEvent.fire();
},
})Explanation : –
$A.get(‘e.c:applicationEvent’); – Finds the event with the name provided after c: and in our case it it applicationEvent.
setParams : – is used to send the parameters to the parent component if we are using any attribute in the event. In our case we have used attribute testWord
fire() :- Executes the eventStep 4: – Handle the Event in any Component
A single line of code to handle the event into the component
<aura:handler event=”c:applicationEvent” action=”{!c.doHandleCompEvent}” />
Log In to reply.