javascript / expert
Snippet
Object-Oriented EventTarget Subclassing for Decoupled Svelte State Messaging
Extends the native browser EventTarget class using private class fields (#state) to create a decoupled event-driven state emitter. Svelte components can subscribe to statechange events via standard addEventListener logic or reactive wrappers.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export class SvelteStateBridge extends EventTarget {#state;constructor(initialState) {super();this.#state = initialState;}get state() {return this.#state;}update(patch) {const previous = { ...this.#state };this.#state = Object.assign({}, this.#state, patch);this.dispatchEvent(new CustomEvent('statechange', { detail: { current: this.#state, previous } }));}}
svelte
Breakdown
1
export class SvelteStateBridge extends EventTarget {
Inherits event-handling capability directly from the native browser EventTarget.
2
#state;
Enforces strict encapsulation using JavaScript private class fields.
3
get state() { return this.#state; }
Exposes a read-only getter to safely access internal state snapshots.
4
this.#state = Object.assign({}, this.#state, patch);
Applies immutable state mutation updates to the internal state variable.
5
this.dispatchEvent(new CustomEvent('statechange', { detail: { current: this.#state, previous } }));
Dispatches a custom synthetic event notifying attached Svelte components of updates.