1

I have a lwc that dispatches an event to be received by another lwc that's not in the same DOM tree.

This is my child lwc block of code:

this.dispatchEvent(new CustomEvent('newfilesuccess'));

And this is my listener lwc (not parent):

constructor(){
  super();
  this.addEventListener('newfilesuccess', this.handleFileSuccess);
}
handleFileSuccess = () => {
  console.log('success!');
}

But I can't manage to handle communication between both lwcs. How can I achieve this?

Regards,

1

2 Answers 2

3

For anything other than direct parent-to-child or child-to-parent communication, you need to use a Publish-Subscribe Pattern (this links to an Aura Trailhead). Fortunately, there's already a built-in library for this, called the Lightning Message Service. Basically, you first design a channel that your two components can subscribe to in connectedCallback, and unsubscribe from in disconnectedCallback (to free memory resources). Any component subscribed to the channel will get any notifications published through the publish function. This is interoperable between both Aura and LWC components anywhere in the same DOM, even if they are not directly related in the DOM.

4
  • Thanks! That's just what I needed!
    – molinet
    Commented Apr 5, 2022 at 9:39
  • 1
    @molinet You're welcome!
    – sfdcfox
    Commented Apr 5, 2022 at 9:49
  • Be aware that (as far as I can find) LMS support is still beta in digital experiences (as it has been since Spring '21). This is a concern if you need to use it in a production implementation.
    – Phil W
    Commented Apr 5, 2022 at 11:02
  • It was GA'd in Winter '22 for Aura/LWC sites. May have to flag that document to see if it needs updating Commented Apr 5, 2022 at 11:46
0

If the calling LWC is using light renderMode you could just call a method on the other LWC directly instead of passing an event. Might be useful in a pinch if you don't want the overhead of creating a MessageChannel.

   static renderMode = "light";
...
   window.document
        .querySelector("c-my-lwc-name")
        .myMethod();

The method you are calling on the other LWC must be decorated with @api

You must log in to answer this question.

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