Component Event Example
Here’s a simple use case of using a component event to update an attribute in another component.
- A user clicks a button in the notifier component,
ceNotifier.cmp. - The client-side controller for
ceNotifier.cmpsets a message in a component event and fires the event. - The handler component,
ceHandler.cmp, contains the notifier component, and handles the fired event. - The client-side controller for
ceHandler.cmpsets an attribute inceHandler.cmpbased on the data sent in the event.
The event and components in this example use the default c namespace. If your org has a namespace, use that namespace instead.
The ceEvent.evt component event has one attribute. We’ll use this attribute to pass some data in the event when it’s fired.
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.
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.
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.
The controller retrieves the data sent in the event and uses it to update the messageFromEvent attribute in the handler component.
Add the c:ceHandler component to a c:ceHandlerApp application. Navigate to the application and click the button to fire the component event.
https://MY_DOMAIN_NAME.lightning.force.com/c/ceHandlerApp.app.
If you want to access data on the server, you could extend this example to call a server-side controller from the handler’s client-side controller.
See Also