2

I want to call the parent component's helper function in the child component's controller.

I am thinking of using aura:event to pass the component reference from child and handle it in parent.

I don't know if we can pass the component as a reference as an attribute in event or is there any better way?

1 Answer 1

3

Component events are precisely for this. It bubbles up the chain in this case your parent component can listen to it using a aura:handler and can take appropriate actions.

Instead of passing the component to parent just pass the required attributes and perform operations at parent accordingly.

var compEvent = cmp.getEvent("sampleComponentEvent");
// Optional: set some data for the event (also known as event shape)
// A parameter’s name must match the name attribute
// of one of the event’s <aura:attribute> tags
// compEvent.setParams({"myParam" : myValue });
compEvent.fire();

Please read firing component events

If you still wish to get an instance of the component then use event.getSource() in the parent component.

4
  • 2
    RedDevil is right that it would probably be neat to pass the data you need as attributes on the event. But, also worth noting that the event has a getSource() method which you could use in your event handler to give you a reference to the source component. There's not a hard-and-fast rule on which approach is better
    – Aidan
    Commented Jul 10, 2017 at 8:27
  • My requirement is such that I need to pass component, I have written a function in parent controller which I need to use for the child, if I pass the data I have to rewrite the function but if I am able to pass the component reference then I can pass the component in the helper function and it work for both parent and child. Commented Jul 10, 2017 at 10:05
  • In that case you can do what Aidan said event.getSource() and get the child component.
    – RedDevil
    Commented Jul 10, 2017 at 10:09
  • Thanks just updated the answer just incase if its useful for someone in the future.
    – RedDevil
    Commented Jul 10, 2017 at 17:54

You must log in to answer this question.

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