LWC Custom Event Issue

child-to-parentlightning-eventslightning-web-components

I have a LWC Component A(Child), Whose javascript is dispatching an event like this:

dispatchRefreshImageDetails(imageId)
{
    //imageId contains Full Image URL as from content version object.
    const uploadedImage = new CustomEvent('refreshimagepicture', {
        detail: {
            imageUrl: imageId
        }
    });

    window.dispatchEvent(uploadedImage);
}

I am listening to this event from 2 different parent components say Component B and Component C.

It works very well in Component B, however, doesnt work in Component C.

Below is how I am listening to this event in Component C:

//It has a wire method which directly fetches the Image from sObject
wire(){
}

connectedCallback()
{
        window.addEventListener('refreshimagepicture', this.refreshImagePictureIds);
}
disconnectedCallback()
{
       window.removeEventListener('refreshimagepicture', this.refreshImagePictureIds);
}

refreshImagePictureIds=(event)=>{
   const ImageDetail = event.detail.imageUrl;
}

The issue I am facing here is that the event is not getting listened correctly, and any console log statements written in refreshImagePictureIds doesn't execute, but the console log statements in connectedCallback executes successfully. So, by default when the DOM is initiated, the data as in wire method is shown, which is fine. However, when i travers to other pages in my LWR Community and get back to this particular page in concern, I would expect the event details to be displayed appropriately.

Any help would be appreciated. Thank you.

Best Answer

From the answer to my question adding bubbles true to your customevent should notify the grandparent component. A good post on Salesforce Developer Blog How Events Bubble in Lightning Web Components

{ bubbles: true, composed: false }

Use this configuration to bubble up an event inside the component’s template, creating an internal event. You can also use this configuration to handle an event in a component’s grandparent.

bubbles A Boolean value indicating whether the event bubbles up through the DOM or not. Defaults to false.

On child component if you update your code like below:

const uploadedImage = new CustomEvent('refreshimagepicture', { bubbles:true, detail: { imageUrl: imageId } });

    this.dispatchEvent(uploadedImage);