Http://stackoverflow.com/questions/1160193/using-jquerys-datastore-vs-expando-properties
Question:
I'm developing code using jquery and need to store data associated with certain DOM elements. There are a bunch of other questions aboutHowTo store arbitrary data with an HTML element, but I'm more interested in why I wowould pick one option over the other.
Say, for the sake of extremely simplified argument, that I want to store a "linenumber" property with each row in a table that is "interesting ".
Option 1 wocould be to just set an expando property on each Dom element (I hope I'm using the term 'pando' correctly ):
$('. Interesting-line').Each(Function(I){This.Linenumber=I;});
Option 2 wocould be to use jquery's data () function to associate a property with the element:
$('. Interesting-line').Each(Function(I){$(This).Data('Linenumber',I);});
Ignoring any other login comings of my sample code, are there strong reasons why you wowould choose one means of storing properties over the other?
Answer:
Using$. Data
Will protect you from memory leaks.
In IE, When you assign a javascript object to an expando property on a DOM element, cycles that cross that link are not garbage collected. if your JavaScript Object holds a reference to the DOM object, the whole cycle will leak. it's entirely possible to end up with hidden references to DOM objects, due to closures, so you may leak without realizing it.
The jquery datastore is set up to prevent these cycles from forming. if you use it, you will not leak memory in this way. your example will not leak because you are putting primitives (strings) on the DOM element. but if you put a more complex object there, you risk leaking.
Use$. Data
So you won't have to worry.
See also:
Circular references
Circular references are the root of nearly every leak. normally, script engines handle circular references through their garbage collectors, but certain unknowns can prevent their heuristics from working properly. the unknown in the case of IE wocould be the status of any DOM elements that a portion of script has access. the basic principle wocould be as follows:
Http://msdn.microsoft.com/en-us/library/bb250448%28VS.85%29.aspx