Newer Version Available

This content describes an older version of this product. View Latest

Component Event Example

Here’s a simple use case of using a component event to update an attribute in another component.
  1. A user clicks a button in the notifier component, ceNotifier.cmp.
  2. The client-side controller for ceNotifier.cmp sets a message in a component event and fires the event.
  3. The handler component, ceHandler.cmp, contains the notifier component, and handles the fired event.
  4. The client-side controller for ceHandler.cmp sets an attribute in ceHandler.cmp based 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.

Note

Component Event

The ceEvent.evt component event has one attribute. We’ll use this attribute to pass some data in the event when it’s fired.

Notifier Component

The c:ceNotifier component uses aura:registerEvent to declare that it may fire the component event.

The button in the component contains a press 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.

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.

The controller retrieves the data sent in the event and uses it to update the messageFromEvent attribute in the handler component.

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.

https://<myDomain>.lightning.force.com/c/ceHandlerApp.app, where <myDomain> is the name of your custom Salesforce domain.

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.