javascript / expert
Snippet
Encapsulating Private Svelte Action States using WeakMap Instance Registries
Attaching metadata properties directly to DOM elements in Svelte actions risks scope pollution and memory leaks. Utilizing a module-scoped WeakMap couples internal action states strictly to DOM element references while allowing automatic garbage collection upon element removal.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const actionInstances = new WeakMap();export function createIsolatedAction(config) {return function action(node) {const state = Object.preventExtensions({ id: Symbol(), node, active: true });actionInstances.set(node, state);return {destroy() {const inst = actionInstances.get(node);if (inst) inst.active = false;actionInstances.delete(node);}};};}
svelte
Breakdown
1
const actionInstances = new WeakMap();
Declares a module-level WeakMap where keys are DOM element references holding private state.
2
const state = Object.preventExtensions({ id: Symbol(), node, active: true });
Creates an instance state object that cannot be expanded with arbitrary external properties.
3
actionInstances.set(node, state);
Registers the element node as a weak key mapping to its private state without preventing GC.
4
actionInstances.delete(node);
Removes the reference explicitly from the weak registry during Svelte component destruction.