简体   繁体   中英

Aura.js Lightning Components: Firing a nested/child component's methods from the super/parent component?

I'm having issues communicating to a nested component. I would like a component to be able to run a method in the nested-component's controller.js (or helper). I have tried both events and via and no luck. Here is the example markup:

<!-- myEvent.evt -->
<aura:event type="APPLICATION">
</aura:event>

<!-- super-component -->
<aura:component>
    <aura:registerEvent name="myEventName" type="c:myEvent"/>
    <c:my_Nested_Component />
    <ui:button press="{!fireEvent}"
<aura:component>



//super-component_controller.js
({
  fireEvent: function(component){
    var myEvent = component.getEvent("myEventName");
    myEvent.fire();
    console.log('event fired');
  }
})

------------------------------------------

<!-- nested-component -->
<aura:component>
    <aura:handler name="myEventName" event="c:c:myEvent" action="{!c.gotEvent}" />

<aura:component>


//nested-component_controller.js
({
  gotEvent: function(component, event){
    console.log('received event!');
  }
})

This does not work. I tried the same exact code that I placed on the nested-component on a super-super-component, and it worked perfectly.The super-super component received the event. But the nested component is not able to. I figured this had to do with events only bubbling up (though the documentation does say that that is only the case with Component events, not application events).

So the other option I read online is using . I tried doing this, but this too did not work for speaking to a nested component.

How can a parent component cause a method on the nested component to fire?

Thank you

This issue was answered here: https://salesforce.stackexchange.com/questions/108544/lightning-components-firing-a-nested-child-components-methods-from-the-super-p

The problem was that I was using component.getEvent() instead of $A.get(), which is required for Application level events. Additionally, the name of the registered event is not the way to reference the event from the handler, but rather using it's actual file name, like so:

//super-component_controller.js
 ({
  fireEvent: function(component){
  var myEvent = $A.get("e.c:myEvent");
  myEvent.fire();
  console.log('event fired');
  }
})

<!-- nested-component -->
<aura:component>
   <aura:handler event="c:myEvent" action="{!c.gotEvent}" />
<aura:component>

Thank you to @MohithShrivastava for figuring this one out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM