javascript / expert
Snippet
Type-Safe Reactive Event Emitter with Private Symbol Keys and WeakRefs
Event emitter implementations can easily cause memory leaks if listeners retain strong references to discarded objects. This expert pattern creates a custom event publishing channel using native ES JavaScript WeakRef primitives alongside private class fields and Symbol identifiers. Callbacks held in WeakRefs can be garbage collected when no other strong references exist, while stale references are cleaned up automatically during publish iterations.
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
const EVENT_KEY = Symbol('CUSTOM_SYSTEM_EVENT');export class ReactiveChannel {#listeners = new Set();subscribe(handler) {const reference = new WeakRef(handler);this.#listeners.add(reference);return () => this.#listeners.delete(reference);}publish(payload) {for (const refItem of this.#listeners) {const handler = refItem.deref();if (handler) {handler({ type: EVENT_KEY, payload });} else {this.#listeners.delete(refItem);}}}}
vue
Breakdown
1
const EVENT_KEY = Symbol('CUSTOM_SYSTEM_EVENT');
Creates a unique, unforgeable Symbol identifier to serve as the immutable event topic key.
2
#listeners = new Set();
Declares a private ECMAScript class field holding a Set of listener reference wrappers.
3
const reference = new WeakRef(handler);
Wraps the callback handler in a WeakRef object to allow garbage collection of the target function.
4
const handler = refItem.deref();
Attempts to resolve the target callback function if it has not yet been garbage collected.
5
this.#listeners.delete(refItem);
Prunes dead WeakRef instances from the listener Set when deref() returns undefined.