Component event in lightning component(AURA)
Component Events are fired by the child components and handled by the parent component.
A lightning framework is an event driven architecture i.e communication between the components takes place by using events.
In the below example will how to fire events from the child component and handle them in the parent component.
CompEvent.evt:-
<aura:event type="COMPONENT" description="Event template" >
<aura:attribute name="storeMessage" type="String"/>
</aura:event>
ChildComp.cmp
<aura:component >
<aura:registerEvent name="regInChild" type="c:CompEvent"/>
<aura:attribute name="textMessage" type="String" default="Part from child comp"/>
<lightning:button label="Click To Fire" onclick="{!c.doHandleEvent}"/>
</aura:component>
Javascript controller:
({
doHandleEvent : function(component, event, helper) {
var cmpEvnt=component.getEvent("regInChild");
cmpEvnt.setParams({
storeMessage : component.get("v.textMessage")
});
cmpEvnt.fire();
}
})
ParentComp.cmp
<aura:component >
<aura:handler name="regInChild" event="c:CompEvent" action="{!c.doHandleFromChild}"/>
<aura:attribute name="parentMessage" type="String" />
<c:ChildComp/>
{!v.parentMessage}
</aura:component>
Javascript controller:
({
doHandleFromChild : function(component, event, helper) {
var valueFromEvent=event.getParam("storeMessage");
component.set("v.parentMessage",valueFromEvent);
}
})