0

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.

2
  • Are component B and C direct parents of component A? Also why are you using window and not this?
    – tugce
    Sep 6, 2023 at 16:11
  • Sorry for the confusion, Component C is the outer container, which hosts Component B. Component B hosts Component A. So, Component A is child and both B and C are parent components.
    – Ravi Kumar
    Sep 6, 2023 at 16:14

1 Answer 1

1

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);
1
  • Thank you. It works.
    – Ravi Kumar
    Sep 6, 2023 at 16:34

You must log in to answer this question.

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