Node RegistryLoading saved progress…

Node Registry

Sometimes you need to attach extra data to a DOM node — a cached measurement, a parsed config, a "seen" flag — without writing it onto the element itself. The catch: when that node leaves the page and nothing else references it, your stored data must not keep it alive. Implement nodeRegistry(), which returns a small object that associates arbitrary values with DOM nodes and lets those nodes be garbage-collected once they are gone. The implementation detail that makes this safe is a WeakMap, which holds its keys weakly.

Signature

function nodeRegistry(): {
  set(node: Node, value: unknown): void;   // associate value with node
  get(node: Node): unknown;                 // value, or undefined if absent
  has(node: Node): boolean;                 // is this node registered?
  delete(node: Node): boolean;              // remove; true if it existed
};

Keys are DOM nodes, compared by identity. Values can be anything. The registry exposes no way to list or count the nodes it holds.

Examples

const reg = nodeRegistry();
const a = document.createElement('div');
const b = document.createElement('div');

reg.set(a, { clicks: 1 });
reg.set(b, { clicks: 9 });

reg.get(a);     // → { clicks: 1 }   (each node keeps its own value)
reg.has(b);     // → true
reg.delete(a);  // → true
reg.get(a);     // → undefined
const reg = nodeRegistry();
const node = document.createElement('span');

reg.get(node);          // → undefined  (never registered)
reg.set(node, 0);
reg.has(node);          // → true       (a stored 0 is still "present")

Notes

  • Keyed by identity. Two different nodes are always distinct keys, even if they are the same tag. Storing on one must never affect another.
  • Values can be anything. Objects, numbers, 0, false, null — all valid. has reports presence, not truthiness.
  • No leaks. The registry must not retain a strong, enumerable collection of nodes. A node that drops out of the DOM and loses all other references should be collectable.
  • No enumeration. There is intentionally no size, keys(), or forEach — exposing one would defeat the whole point.
  • Detached nodes are fine. A node created with document.createElement and never inserted is a valid key.
Loading editor…