javascript / expert
Snippet
Extending EventTarget Classes for Polymorphic Controller Subscriptions in Svelte Components
Encapsulating component logic within custom EventTarget classes provides encapsulated private state (#field) while providing standard event bus capability suited for Svelte context injection.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export class FormStateController extends EventTarget {#state = Object.seal({ valid: false, value: '' });constructor(initialValue) {super();this.#state.value = initialValue;}updateValue(val) {this.#state.value = val;this.#state.valid = val.trim().length > 0;this.dispatchEvent(new CustomEvent('statechange', { detail: { ...this.#state } }));}get snapshot() {return Object.freeze({ ...this.#state });}}
svelte
Breakdown
1
export class FormStateController extends EventTarget {
Inherits native event dispatching capabilities to act as a custom reactivity bus inside Svelte.
2
#state = Object.seal({ valid: false, value: '' });
Defines private class fields sealed against property addition or deletion.
3
this.dispatchEvent(new CustomEvent('statechange', { detail: { ...this.#state } }));
Fires a custom typed DOM event payload to notify subscribers of state mutation.