Working with Events in JavaScript

These are useful and common patterns for working with events in JavaScript.

Events communicate data across components. Events can contain attributes with values set before the event is fired and read when the event is handled.

Fire an Event

Fire a component event or an application event that’s registered on a component.
//Fire a component event
var compEvent = cmp.getEvent("sampleComponentEvent");
compEvent.fire();

//Fire an application event
var appEvent = $A.get("e.c:appEvent");
appEvent.fire();

Get an Event Name

To get the name of the event that’s fired:

event.getSource().getName();

Get an Event Parameter

To get an attribute that’s passed into an event:

event.getParam("value");

Get Parameters on an Event

To get all attributes that are passed into an event:

event.getParams();

event.getParams() returns an object containing all event parameters.

Get the Current Phase of an Event

To get the current phase of an event:

event.getPhase();
If the event hasn’t been fired, event.getPhase() returns undefined. Possible return values for component and application events are capture, bubble, and default. Value events return default. For more information, see:

Get the Source Component

To get the component that fired the event:

event.getSource();

To retrieve an attribute on the component that fired the event:

event.getSource().get("v.myName");

Pause the Event

To pause the fired event:

event.pause();
If paused, the event is not handled until event.resume() is called. You can pause an event in the capture or bubble phase only. For more information, see:

Prevent the Default Event Execution

To cancel the default action on the event:
event.preventDefault();

For example, you can prevent a lightning:button component from submitting a form when it’s clicked.

Resume a Paused Event

To resume event handling for a paused event:

event.resume();
You can resume a paused event in the capture or bubble phase only. For more information, see:

Set a Value for an Event Parameter

To set a value for an event parameter:

event.setParam("name", cmp.get("v.myName");

If the event has already been fired, setting a parameter value has no effect on the event.

Set Values for Event Parameters

To set values for parameters on an event:

event.setParams({
    key : value
});

If the event has already been fired, setting the parameter values has no effect on the event.

Stop Event Propagation

To prevent further propagation of an event:

event.stopPropagation();

You can stop event propagation in the capture or bubble phase only.