On a shop page, the product cards, the cart badge in the header and an analytics script all care when something is added to the cart. If the card calls the badge and the analytics directly, every part has to know about every other. A custom event decouples them: the card announces cart:add from its button, the event bubbles up the page, and anything that cares listens for it, and can even veto it, for example when an item is sold out.
announceAddToCart(source, item) // returns true, or false when a listener cancelled the eventonAddToCart(target, handler) // returns a stop functioncartCounter(root, output) // returns a stop function
item: a plain object such as { sku: "nb-1", quantity: 2 }.
handler(detail, event): called for each cart:add event that reaches target.
announceAddToCart dispatches a CustomEvent named "cart:add" from source, so event.target is source.
Its detail has the item's fields, but is a frozen copy: not the caller's object, and no listener can change it.
The event bubbles (a listener on document hears it), crosses shadow DOM boundaries (a listener outside a shadow root hears it), and can be cancelled.
Listeners run during the call, before announceAddToCart returns. It returns false when a listener called preventDefault, and true otherwise.
A listener that throws does not stop the other listeners or the call.
onAddToCart calls handler(detail, event) for every cart:add that reaches target, and for nothing else. Its stop function removes only that handler (calling it twice is harmless).
cartCounter sets output's text to "0", then to the running total of quantities of the cart:add events reaching root. An item without quantity counts as 1. Events already cancelled when they reach root are not counted.
Each counter keeps its own total; after its stop function is called, it no longer changes.