8

Below code works fine for passing reference of method while creating component dynamically or you can click me for help

cmp.getReference("c.handlePress")

how to pass reference of method if i'm not creating my component dynamically.

<c:myComp method={"c.hadelpress"} />

i want something like above

2 Answers 2

13

you need to define method attribute of type Aura.Action in your child component and pass the {!c.methodName} to your child component from the parent/container component.

myComp.cmp

<aura:component>
    <aura:attribute name="method" type="Aura.Action" />
    <button onclick="{!v.method}" type="button"> click me </button>
</aura:component>

main.cmp

<aura:component>
    <c:myComp method="{!c.handlepress}" />
</aura:component>

maincontroller.js:

({
    "handlepress" : function(cmp,event,helper) {
        console.log('button click');
    }
})
5

Apart from praveen's solution you can try this one if you have a registered event. If you want to call passed function from controller and helper then use following code:

Handler function can be assigned to registered event in the component.

Suppose in c:someComponent I have

<aura:registerEvent name="onSomeThing" type="c:someEvent"/>

then, I can write as follows-

<c:someComponent onSomeThing="{!c.handleSomeThing}" />
2
  • 1
    Saurabh, there's no need to call the $A.enqueueAction() method for this case. The parent controller method will be correctly binded to the child component's onclick event when passed as attribute. I have updated your answer answer.
    – Praveen
    Dec 23, 2016 at 9:24
  • Ok. @Praveen $A.enqueueAction() is needed only if function is to be called from controller or helper otherwise what you said is right. Please see following question salesforce.stackexchange.com/questions/146575/… Dec 23, 2016 at 10:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .