The c:ceNotifier component uses aura:registerEvent to declare that it may fire the component event.
The button in the component contains an onclick browser event that is wired to the fireComponentEvent action in the client-side controller. The action is invoked when you click the button.
1<!--c:ceNotifier-->2<aura:component>3 <aura:registerEvent name="cmpEvent" type="c:ceEvent"/>45 <h1>Simple Component Event Sample</h1>6 <p><lightning:button7 label="Click here to fire a component event"8 onclick="{!c.fireComponentEvent}" />9 </p>10</aura:component>
The client-side controller gets an instance of the event by calling cmp.getEvent("cmpEvent"), where cmpEvent matches the value of the name attribute in the <aura:registerEvent> tag in the component markup. The controller sets the message attribute of the event and fires the event.
1/* ceNotifierController.js */2{3 fireComponentEvent : function(cmp, event){4 // Get the component event by using the5 // name value from aura:registerEvent6 var cmpEvent = cmp.getEvent("cmpEvent");7 cmpEvent.setParams({8 "message" : "A component event fired me. " +9 "It all happened so fast. Now, I'm here!"});10 cmpEvent.fire();11}12}
Handler Component
The c:ceHandler handler component contains the c:ceNotifier component. The <aura:handler> tag uses the same value of the name attribute, cmpEvent, from the <aura:registerEvent> tag in c:ceNotifier. This wires up c:ceHandler to handle the event bubbled up from c:ceNotifier.
When the event is fired, the handleComponentEvent action in the client-side controller of the handler component is invoked.
1<!--c:ceHandler-->2<aura:component>3 <aura:attribute name="messageFromEvent" type="String"/>4 <aura:attribute name="numEvents" type="Integer" default="0"/>56 <!-- Note that name="cmpEvent" in aura:registerEvent7 in ceNotifier.cmp -->8 <aura:handler name="cmpEvent" event="c:ceEvent" action="{!c.handleComponentEvent}"/>910 <!-- handler contains the notifier component -->11 <c:ceNotifier />1213 <p>{!v.messageFromEvent}</p>14 <p>Number of events: {!v.numEvents}</p>1516</aura:component>
The controller retrieves the data sent in the event and uses it to update the messageFromEvent attribute in the handler component.
1/* ceHandlerController.js */2{3 handleComponentEvent : function(cmp, event){4 var message = event.getParam("message");56 // set the handler attributes based on event data7 cmp.set("v.messageFromEvent", message);8 var numEventsHandled = parseInt(cmp.get("v.numEvents")) + 1;9 cmp.set("v.numEvents", numEventsHandled);10}11}
Put It All Together
Add the c:ceHandler component to a c:ceHandlerApp application. Navigate to the application and click the button to fire the component event.