javascript / expert
Snippet
Subclassing Native EventTarget for Strongly-Typed Context Services
Extending the browser's native EventTarget class allows Svelte context services to implement custom decoupled event dispatching while hiding mutable properties behind immutable getters.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export class DomainBus extends EventTarget {#state;constructor(initialState) {super();this.#state = initialState;}get state() {return Object.freeze({ ...this.#state });}dispatchDomainEvent(type, detail) {this.#state = { ...this.#state, ...detail };this.dispatchEvent(new CustomEvent(type, { detail }));}}export function setDomainContext(key, bus) {if (!(bus instanceof DomainBus)) throw new Error('Must pass DomainBus instance');return bus;}
svelte
Breakdown
1
export class DomainBus extends EventTarget {
Subclasses the native DOM EventTarget to derive built-in event management primitives.
2
get state() {
Exposes state via an immutable getter returning a frozen shallow copy of internal values.
3
this.dispatchEvent(new CustomEvent(type, { detail }));
Triggers native dom events using custom event structures to notify subscribers.
4
if (!(bus instanceof DomainBus)) throw new Error('Must pass DomainBus instance');
Verifies OOP instance compatibility prior to passing objects down Svelte context hierarchies.