+ Start a Discussion
Engine ForceEngine Force 

Component Handling Its Own Event - get id from the iteration

On this documentation link: https://developer.salesforce.com/trailhead/lightning_components/lightning_components_events_handle

it says, a component can also handle its own event. Simply include an aura:registerEvent and aura:handler in that component.

Let's say I have a list of accounts and on clicking the account name, I want to display its contact list.

<aura:iteration items="{!v.accounts}" var="acc">    
        <div onclick="{!c.showContacts}" class="row primary">{!acc.Name}</div>     
    </aura:iteration>

In the showContacts controller action, how do I set the parameter to the event which takes an account object?
// How do I set acct below?
var updateEvent = component.getEvent("showContacts");
      updateEvent.setParams({ "account": acct }).fire();

var acct = component.get("v.acc.id");
this doesn't work.

I know how to do this via a sub-component that shows the account name, register the onclick event and handle it in the main component. Just wondering how you do this in the component itself since the logic is really simple and do not want to use a subcomponent for that one line of code.

Please advise.


 
thoriyasthoriyas

You can do this using <aura:methods>

<aura:method name="sampleMethod" action="{!c.doAction}" access="PUBLIC" 
  description="Sample method with parameters"> 
    <aura:attribute name="param1" type="String" default="parameter 1"/> 
</aura:method>
 
<aura:iteration items="{!v.accounts}" var="acc">    
        <div onclick="sampleMethod({!acc.id})" class="row primary">{!acc.Name}</div>     
    </aura:iteration>
({
    doAction : function(cmp, event) {
        var params = event.getParam('arguments');
        if (params) {
            var param1 = params.param1;
            // add your code here
        }
    }
})

Refre this: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/ref_tag_method.htm
Kt YadavKt Yadav
Hi,
I am new to lightning and i need to understand  the scenarios or use cases where "Component Handling Its Own Event" is required.Why do we need that because inisde the same component every attribute is available so what purpose we are achieving here using own event?