Custom Events With EventTarget
Build a tiny pub/sub with EventTarget and CustomEvent so modules communicate through real events instead of ad-hoc callbacks.
Code
class Store extends EventTarget {
#state = { count: 0 };
get state() {
return { ...this.#state };
}
increment(by = 1) {
this.#state = { count: this.#state.count + by };
// CustomEvent 携带 detail 载荷
this.dispatchEvent(new CustomEvent('change', { detail: this.state }));
}
}
const store = new Store();
store.addEventListener('change', (event) => {
console.log('change ->', event.detail.count);
});
store.increment();
store.increment(4);
store.increment(5);
// 一次性监听:once 自动移除
store.addEventListener('change', () => console.log('fire once'), { once: true });
store.increment();
store.increment();Output
Captured from a sandboxed run of this snippet in the build pipeline.
change -> 1
change -> 5
change -> 10
change -> 11
fire once
change -> 12Inside the snippet
Custom Events With EventTarget keeps everything in the class Store.
Top-level bindings store hold the demo state — nothing sits inside a function scope.
What comes back is a new object, not a reference to anything passed in.
Putting it to use
The demo output is labeled (change ->, fire once), so every printed line maps back to its originating operation.
Core lines
store.addEventListener('change', (event) => {
console.log('change ->', event.detail.count);
});
this.dispatchEvent(new CustomEvent('change', { detail: this.state }));
return { ...this.#state };
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `store`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.