Creating. new CustomEvent('cart:add', { detail }) makes an event whose detail carries any value, by reference. Also pass the flags you need, because each defaults to false:
bubbles: trueso ancestors and delegates hear it;cancelable: trueso a listener can veto withpreventDefault();composed: trueso it crosses shadow-root boundaries.
You can also subclass Event (class AddEvent extends Event) and put typed fields on it instead of detail.
Dispatching. target.dispatchEvent(event) runs the listeners synchronously and returns false if the event was cancelable and some listener canceled it. That return value is how a component asks permission ("may I close?") before acting. An event can't be dispatched while it's already being dispatched (InvalidStateError).
Non-DOM targets. new EventTarget(), or a class that extends it, gives any object addEventListener() and dispatchEvent(): a store, a WebSocket wrapper, a media controller. Such targets have no parent, so nothing propagates. The constructor arrived in Chrome 64, Firefox 59 and Safari 14.
isTrusted is true when the browser dispatched the event because of real input or its own algorithms, and false for anything from dispatchEvent(), including el.click(). It matters because:
- only trusted
keydown,mousedown,pointerdown,pointerupandtouchendevents grant user activation, which activation-gated APIs such asrequestFullscreen()require; - events notify; they don't cause actions. A synthetic
keydowntypes nothing. The exception is activation behaviour: aMouseEventnamedclickfollows a link or toggles a checkbox even when untrusted.
Name custom events so they can't clash with built-in ones, for example with a prefix (cart:add).