Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

addEventHandler()

Dynamically adds an event handler for a component or application event.

Signature

addEventHandler(String event, function handler, String phase, Boolean includeFacets)

Parameters

event
Type: String
The name of the event to handle. For a component event, set this argument to match the name attribute of the aura:registerEvent tag. For an application event, set this argument to match the event descriptor, namespace:eventName.
handler
Type: function
The handler for the event. There are two format options for this argument.
  • To use a controller action, use the format: cmp.getReference("c.actionName").
  • To use an anonymous function, use the format: function(auraEvent) { // handling logic here }
phase
Type: String
Optional. The event bubbling phase for which to add the handler. The default value is "bubble".
includeFacets
Type: Boolean
If true, attempts to catch events generated by components transcluded by facets; for example v.body.

Sample Code

1// For component event, first param matches name attribute in <aura:registerEvent> tag
2cmp.addEventHandler("compEvent", cmp.getReference("c.handleEvent"));
3
4// For application event, first param is event descriptor, "c:appEvent"
5cmp.addEventHandler("c:appEvent", cmp.getReference("c.handleAppEvent"));
6
7// Anonymous function handler for component event
8cmp.addEventHandler("compEvent", function(auraEvent) {
9    // add handler logic here
10    console.log("Handled the component event in anonymous function");
11});