javascript / expert
Snippet
Memory-Efficient Metadata with WeakMap
WeakMap allows associating private metadata with DOM nodes without preventing garbage collection. Unlike a standard Map, if the DOM node is removed and no other references exist, the metadata is automatically cleaned up, which is vital for preventing leaks in dynamic UIs.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const nodeMetadata = new WeakMap();export function enhancedAction(node, params) {nodeMetadata.set(node, {initialWidth: node.offsetWidth,observer: new ResizeObserver(() => handle(node))});return {destroy() {nodeMetadata.get(node).observer.disconnect();nodeMetadata.delete(node);}};}
svelte
Breakdown
1
const nodeMetadata = new WeakMap();
Creates a weak-reference collection where keys (DOM nodes) can be garbage collected.
2
nodeMetadata.set(node, { ... });
Stores complex objects linked to the node without modifying the node object itself directly.