- A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event.
- Can only be registered in the child component and handled in the parent component.
- Define an event
<!–c:ceEvent–>
<aura:event type=”COMPONENT”>
<aura:attribute name=”message” type=”String”/>
</aura:event>
- Register the event in child component.
<!–c:childCmp–>
<aura:component>
<aura:registerEvent name=”cmpEvent” type=”c:ceEvent”/>
<h1>Simple Component Event Sample</h1>
<p><lightning:button
label=”Click here to fire a component event”
onclick=”{!c.fireComponentEvent}” />
</p>
</aura:component>
- on clicking the button, client side function will be executed and fires the component event.
/* childCmpController.js */
{
fireComponentEvent : function(cmp, event) {
// Get the component event by using the
// name value from aura:registerEvent
var cmpEvent = cmp.getEvent(“cmpEvent”);
cmpEvent.setParams({
“message” : “A component event fired me. ” +
“It all happened so fast. Now, I’m here!” });
cmpEvent.fire();
}
}
- Now time to write the handler component that will listen to the component event.
<!–c:parentCmp–>
<aura:component>
<aura:attribute name=”messageFromEvent” type=”String”/>
<aura:attribute name=”numEvents” type=”Integer” default=”0″/>
<!– Note that name=”cmpEvent” in aura:registerEvent
in childCmp.cmp –>
<aura:handler name=”cmpEvent” event=”c:ceEvent” action=”{!c.handleComponentEvent}”/>
<!– parent handler contains the child component –>
<c:childCmp />
<p>{!v.messageFromEvent}</p>
<p>Number of events: {!v.numEvents}</p>
</aura:component>
- When the child component fires the event, the parent will listen and executes the handler. Which in turn will execute the “handleComponentEvent” action. To access the attribute of the event in handler use event.getParam(“message”);
/* parentCmpController.js */
{
handleComponentEvent : function(cmp, event) {
var message = event.getParam(“message”);
// set the handler attributes based on event data
cmp.set(“v.messageFromEvent”, message);
var numEventsHandled = parseInt(cmp.get(“v.numEvents”)) + 1;
cmp.set(“v.numEvents”, numEventsHandled);
}
}