Newer Version Available

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

Event Handling in Base Lightning Components

Base components are lightweight and closely resemble HTML markup. They follow standard HTML practices by providing event handlers as attributes, such as onfocus, instead of registering and firing Lightning component events, like components in the ui namespace.

Because of their markup, you might expect to access DOM elements via event.target or event.currentTarget. However, this type of access breaks encapsulation because it provides access to another component’s DOM elements, which are subject to change.

LockerService, which will be enabled for all orgs in Summer ’17, enforces encapsulation. Use the methods described here to make your code compliant with LockerService.

To retrieve the component that fired the event, use event.getSource().

Retrieve a component attribute that’s passed to the event by using this syntax.

Reusing Event Handlers

event.getSource() helps you determine which component fired an event. Let’s say you have several buttons that reuse the same onclick handler. To retrieve the name of the button that fired the event, use event.getSource().get("v.name").

Retrieving the Active Component Using the onactive Handler

Components, such as lightning:tab and lightning:menuItem, support the onactive handler so that you can obtain a reference to the target component when it becomes active. Clicking the component multiple times invokes the handler once only.

For example, you can toggle a check mark on a menu item in a lightning:buttonMenu component when it’s clicked.

If you only need the ID or value of the tab and you don’t need a reference to the target component, use the onselect event handler.

Note

Retrieving the ID and Value Using the onselect Handler

Some components provide event handlers to pass in events to child components, such as the onselect event handler on the following components.
  • lightning:buttonMenu
  • lightning:tabset
Although the event.detail syntax continues to be supported, we recommend that you update your JavaScript code to use the following patterns for the onselect handler as we plan to deprecate event.detail in a future release.
  • event.getParam("id")
  • event.getParam("value")
For example, you want to retrieve the value of a selected menu item in a lightning:buttonMenu component from a client-side controller.
Similarly, to retrieve the ID of a selected tab in a lightning:tabset component:

If you need a reference to the target component, use the onactive event handler instead.

Note