How to listen for custom events defined web component
If your compound element <my-checkreport>
uses a Shadow DOM to embed its content (<my-checkbox>
, label, styling...), dispatched events from an inner element (here <my-checkbox>
) will be fired inside the (container's) Shadow DOM.
Therefore, you should add the event listener to the Shadow DOM's root of the compound custom element (this.shadowRoot
) instead of to the element (this
) itself. In <my-checkreport>
:
connectedCallback(){
...
this.shadowRoot.addEventListener("check", function (e) {
console.log('listend to check event');
console.log(e);
});
}
More on Shadow DOM:
- For the beginners: Presentation by Eric Bidelman
- Good summary: Synthesis by Hayato Ito
- Specs: W3C Working Draft
- SO: questions and answers
For others who end up here, the specific property you're looking for to break out of the shadow root 'jail' is "composed".
So:
this.checkEvent = new CustomEvent("check", {
bubbles: true,
cancelable: false,
composed: true
});
You can also add another property, "detail" which will carry custom data on the event, if you like.
More info here: composed property