Can I, and if so, how can I associate javascript objects with DOM nodes? My requirements:
I was thinking about doing it with a global array that holds the data and putting the indexes in attributes of the nodes, but that would leak memory because there's still a reference from the array to the data when the nodes aren't in th DOM anymore. It's for a web application, so that could be an issue.
Well, jQuery has the data system, which you could give a try. They say it's free from memory leaks.
Perfect use case for the WeakMap, assuming your targeting newer browsers (chrome 36, edge 12, IE 11, firefox 36, safari 7.1):
let map = new WeakMap();
let node = document.getElementById("unicorn");
let data = {};
window.map.set(node, data);
this wont leak since the keys of the WeakMap are weakly referenced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With