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!
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 globalself
(ie thewindow
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:
global:
self
(synonym forwindow
or a worker in other contexts); coordinate events here that are intended to be tightly coupled across many things--it is by far the simplest organization scheme when very specific coordinated systems are needed; simply listen and dispatch events here for this scenario; add and remove the event listeners in theconnectedCallback
anddisconnectedCallback
. Then either dispatch anywhere with bubbling or directlyself.dispatchEvent('type', {detail:...})
and bubbling, etc is no longer necessary.nodes: at any level of the tree, when a component has any state or events of any kind, handle the scenario and create an appropriate message as the
event.detail
and a sensible name as theevent.type
, then dispatch this from the node that is handling that logic. Other nodes--on themselves for parent nodes, etc--can watch theevent.bubble
up, and when dispatching from shadow nodes, those events can use thecomposed:true
flag to allow continuation of the event outside the shadowRoot. Or the element can handle internal events and dispatch a new type of event and payload that fits that type.