Custom Events With EventTarget

Build a tiny pub/sub with EventTarget and CustomEvent so modules communicate through real events instead of ad-hoc callbacks.

JavascriptData Integrity

Code

javascriptsnippet
27 lines
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 -> 12

Inside 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

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`.