Application Event Example
Here’s a simple use case of using an application event to update an attribute in another component.
- A user clicks a button in the notifier component,
aeNotifier.cmp. - The client-side controller for
aeNotifier.cmpsets a message in a component event and fires the event. - The handler component,
aeHandler.cmp, handles the fired event. - The client-side controller for
aeHandler.cmpsets an attribute inaeHandler.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 aeEvent.evt application event has one attribute. We’ll use this attribute to pass some data in the event when it’s fired.
The aeNotifier.cmp notifier component uses aura:registerEvent to declare that it may fire the application event. The name attribute is required but not used for application events. The name attribute is only relevant for component events.
The button in the component contains a onclick browser event that is wired to the fireApplicationEvent action in the client-side controller. Clicking this button invokes the action.
The client-side controller gets an instance of the event by calling $A.get("e.c:aeEvent"). The controller sets the message attribute of the event and fires the event.
The aeHandler.cmp handler component uses the <aura:handler> tag to register that it handles the application event.
The handler for an application event won’t work if you set the name attribute in <aura:handler>. Use the name attribute only when you’re handling component events.
When the event is fired, the handleApplicationEvent 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.
The aeContainer.cmp container component contains the notifier and handler components. This is different from the component event example where the handler contains the notifier component.
You can test this code by adding <c:aeContainer> to a sample aeWrapper.app application and navigating to the application.
https://MY_DOMAIN_NAME.lightning.force.com/c/aeWrapper.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