Use WeakMap to store data for DOM nodes
ES6 WeakMap
is a unique data structure in Javascript. It is similar to a Map
but does not prevent the garbage collector from deleting its keys.
For this, it is well-suited to hold some additional data for objects, without needing to worry about memory leaks.
Store data for a DOM node
If you need to store some data for a DOM node, you have a few choices.
First, you can use a Map
that has the DOM node as the key. This works, but what if the DOM node is removed from the document, and there are no other references to it? It is a possible memory leak.
Second, you can store the data as data-
attributes. This practice prevents memory leaks, but you run the risk of clashing attribute names if multiple independent modules use this approach to store data.
And then you can use WeakMap
, which solves both these problems.
Store data using WeakMap
To store data for a DOM node, set
the data with the node as the key:
let map = new WeakMap();
...
map.set(node, data); // data can be anything
To retrieve the data later, use has
and get
:
map.has(node); // Is there data for node?
map.get(node); // Get the data, or undefined
Contrary to using a Map
, this solution is not prone to leaking, and unlike the data-
attributes it does not mutate the node in any way.