javascriptdomweb-componentcustom-eventsnative-web-component

How to catch custom events in Web Components?


To let Web Components communicate with each other, I'm using custom events. Let's imagine the following:

WebComponentA uses or contains WebComponentB which sends a CustomEvent (bubbles: true, composed: true) if a button is clicked. WebComponentA wants to do something if WebComponentB sends this event.

How should I dispatch the event within WebComponentB?

window.dispatchEvent(customEvent);

or

this.shadowRoot.dispatchEvent(customEvent);

How should I catch the event within WebComponentA?

window.addEventListener(custom-event, () => {
);

or

this.shadowRoot.addEventListener(custom-event, () => {
);

Are there any negative effetcts I should consider using one or another?

Thank you!


Solution

  • Dispatch the event on the component itself with bubble: true, composed: true so the event will bubble up to anything watching for it. When you want to very specifically have a lot of predictability and shared state, and I mean this is really a tight coupling desired, then just orchestrate events on global self (ie the window in the browser). Here are a few random examples I hope help, what they're doing is relatively useless just to show an example. The idea overall is to loosely couple things when that makes sense, events simply pass messages relating to state change. The component can always be fairly isolated and whatever context it's operating in can be concerned separately with what it does with that info (both preparing and receiving the model--this is where functional patterns are highly applicable). If more detail is needed or confusing feel free to spell it out and we can try to help.

    Note too that because I didn't setup any shadowRoot the composed flag isn't useful at all in this sample.

    broadly: