Newer Version Available
Event Handling in Base Lightning Components
Because of their markup, you might expect to access DOM elements for base components 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.
Lightning Locker enforces encapsulation. Use the methods described here to make your code compliant with Lightning Locker.
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
When working with tabs, you want to know which one is active. The lightning:tab component enables you to obtain a reference to the target component when it becomes active using the onactive handler . Clicking the component multiple times invokes the handler once only.
1<aura:component>
2 <lightning:tabset>
3 <lightning:tab onactive="{! c.handleActive }" label="Tab 1" id="tab1" />
4 <lightning:tab onactive="{! c.handleActive }" label="Tab 2" id="tab2" />
5 </lightning:tabset>
6</aura:component>1({
2 handleActive: function (cmp, event) {
3 var tab = event.getSource();
4 switch (tab.get('v.id')) {
5 case 'tab1':
6 //do something when tab1 is clicked
7 break;
8 case 'tab2':
9 //do something when tab2 is clicked
10 break;
11 }
12 }
13})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");