3

Can I, and if so, how can I associate javascript objects with DOM nodes? My requirements:

  • real objects, not just JSON-stringified-attributes or so
  • shouldn't leak memory
  • should also work in non-standard browsers like IE8 or so

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.

thejh
  • 44,854
  • 16
  • 96
  • 107
  • @Felix Kling: I want to make objects available through DOM nodes, for example a reference to an input field that I can use later when putting a button with a handler function inside it that needs access to the input field. – thejh Dec 17 '10 at 11:22

3 Answers3

4

Well, jQuery has the data system, which you could give a try. They say it's free from memory leaks.

Spiny Norman
  • 8,277
  • 1
  • 30
  • 55
  • Interesting, I'll look at the jquery source. – thejh Dec 17 '10 at 11:24
  • http://code.jquery.com/jquery-1.4.4.js line 1130 and following look like it does leak memory. – thejh Dec 17 '10 at 11:34
  • Ah, ok - they did what I had in mind, they require you to call their methods for manipulating the DOM in order to prevent memory leaks. If the jQuery guys did it this way, there is propably no better solution. Thanks. – thejh Dec 17 '10 at 11:44
  • For example, in `html()` is this line: `jQuery.cleanData( this[i].getElementsByTagName("*") );` – thejh Dec 17 '10 at 11:47
  • You're welcome, and thanks for posting the extra info as well. Very interesting! – Spiny Norman Dec 17 '10 at 12:02
1

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.

skav
  • 1,400
  • 10
  • 16
0

Since tags doesn't mention jquery. Posting answer with Mootools.

http://mootools.net/docs/core/Element/Element#Element:store

Vishwanath
  • 6,284
  • 4
  • 38
  • 57