Newer Version Available
Event Handling in Base Lightning Components
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().
1<aura:component>
2 <lightning:button name="myButton" onclick="{!c.doSomething}"/>
3</aura:component>1({
2 doSomething: function(cmp, event, helper) {
3 var button = event.getSource();
4
5 //The following patterns are not supported
6 //when you’re trying to access another component’s
7 //DOM elements.
8 var el = event.target;
9 var currentEl = event.currentTarget;
10 }
11})1event.getSource().get("v.name")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").
1<aura:component>
2 <lightning:button label="New Record" name="new" onclick="{!c.handleClick}"/>
3 <lightning:button label="Edit" name="edit" onclick="{!c.handleClick}"/>
4 <lightning:button label="Delete" name="delete" onclick="{!c.handleClick}"/>
5</aura:component>1({
2 handleClick: function(cmp, event, helper) {
3 //returns "new", "edit", or "delete"
4 var buttonName = event.getSource().get("v.name");
5 }
6})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.
1<aura:component>
2 <lightning:buttonMenu alternativeText="Show menu">
3 <lightning:menuItem value="new" onactive="{! c.handleActive }" label="New" checked="true" />
4 <lightning:menuItem value="edit" onactive="{! c.handleActive }" label="Edit" checked="false" />
5 <lightning:menuItem value="delete" onactive="{! c.handleActive }" label="Delete" checked="false" />
6 </lightning:buttonMenu>
7 </aura:component>1({
2 handleActive: function (cmp, event) {
3 var menuItem = event.getSource();
4 menuItem.set("v.checked", !menuItem.get("v.checked"));
5 }
6 })Retrieving the ID and Value Using the onselect Handler
- lightning:buttonMenu
- lightning:tabset
- event.getParam("id")
- event.getParam("value")
1//Before
2var menuItem = event.detail.menuItem;
3var itemValue = menuItem.get("v.value");
4//After
5var itemValue = event.getParam("value");1//Before
2var tab = event.detail.selectedTab;
3var tabId = tab.get("v.id");
4//After
5var tabId = event.getParam("id");