[SalesForce] event.getSource() alternative in LWC? (considering origin reparenting)

Consider below component chain in Aura:

<c:parent>
    <c:child>
        <c:grandChild>

When grandChild fires event, we can get hold of the source component by using event.getSource().
So, if I have an aura:method in grandChild, then I can invoke and pass some data to grandChild by using below in parent JS:

component.find("grandChild").myMethod(someData);

myMethod is aura:method in grandChild

Now lets consider same chain in LWC:

<c-parent>
    <c-child>
        <c-grand-child>

Here, when grand-child fires event, and when we are handling that event in parent, event.target will point to child and not grand-child. This is because of reparenting of event concept in web components.

Use case: child is a reusable component which has many levels of child components. Each of child component triggers different events on init. Other developers can pass the data to grandChild based on event. Now, the child component is a very complicated component which has many different views, so the design of this cannot be changed. We are facing the problem when migrating this component to LWC as we are unable to pass the data using some simple method. I know of other principles like redux, but would like to know if any simpler methods exist.

PFB:
enter image description here

Best Answer

Doesn`t look like there is a cross browser supported way of achieving what you want. Event Standards are either not working or are locked by LWC. So i guess you have to use alternative approaches like message brokers or similiar where grandchild components register and the parent subscribe to events (similiar to pub sub)


Old Answer: I guess you could configure the event as {bubbles:true, composed: true} which would bubble up the event also across shadow boundaries. For concerns by sfdc itself regarding that topic read docs here. So i guess it would make sense to at least call stopPropagation at your parent. Example can be seen here


Related Topic