[SalesForce] How to handle Lightning Web Component Event from Lightning Aura Component

I am firing an event from my Lightning Web Component(LWC). Now I have to receive this event by a Aura Component.

As per the documentation I am able to receive the event if this LWC is enclosed in the Aura Component.

But I am not able to handle this event if LWC and Aura components are independents (LWC is not enclosed in the Aura Component).

I am firing event through Publish Subscriber model.

Thanks,

Best Answer

To simplify things, lets call your LWC, component A, and your Aura component, component B.

Currently your components are independent, thus in tree terms, your component B (Aura) is not an ancestor of the component A (LWC).

There are two quick ways you could fire an event from component A (LWC) to component B (Aura)

1) Create a new Aura component that encapsulates component A (LWC). Component A then would fire a standard DOM event and the new Aura component would listen for the event and then re-fire the event as an application Aura event. Component B would then listen for the event and handle it. Something like this gist.

2) Create a child LWC component, call it componentC, in component B (Aura). Fire the event via pub-sub in component A (LWC). Then in componentC, listen and handle your event then re-fire it as a standard DOM event that would be handled by your Aura component, component B.

More resources:

Events in LWC, Event Propagation, Events from LWC -> Aura