EventTarget With CustomEvent Payloads

Broadcast CustomEvent payloads through a shared EventTarget, the standard DOM event model, and let one-shot listeners remove themselves in their own handler.

JavascriptData Fetching

Code

javascriptsnippet
19 lines
// EventTarget + CustomEvent: 标准 DOM 事件模型,Node 里同样是全局内建
const bus = new EventTarget();

// detail 携带载荷,事件名与载荷形状靠命名约定对齐
bus.addEventListener('cart:updated', (event) => {
  console.log(`cart: ${event.detail.count} items / ${event.detail.total} cents`);
});

const once = (event) => {
  console.log('stale listener got:', event.type);
  bus.removeEventListener('cart:updated', once); // 自移除:只触发一次
};
bus.addEventListener('cart:updated', once);

const emit = (count, total) =>
  bus.dispatchEvent(new CustomEvent('cart:updated', { detail: { count, total } }));

emit(2, 4500);
emit(3, 6800);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

cart: 2 items / 4500 cents
stale listener got: cart:updated
cart: 3 items / 6800 cents

What the code does

Structurally, expect the functions once and emit and nothing else.

Applying it

The primary signature is const once = (event)

The demo output is labeled (stale listener got:), so every printed line maps back to its originating operation.

Statements that matter

bus.addEventListener('cart:updated', (event) => {
console.log(`cart: ${event.detail.count} items / ${event.detail.total} cents`);
});
bus.dispatchEvent(new CustomEvent('cart:updated', { detail: { count, total } }));
bus.addEventListener('cart:updated', once);

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `once`, `emit` at load time.