I was just watching Yehuda's presentation on Evented Programming, and I noticed he was using the .attr() function to store entire DOM elements. This had never even occurred to me before! I've been using .attr() to store simple, text-only data, and using .data() to store DOM elements and more complex textual data.
So now I have some questions (many of which I may have already answered for myself, but I'd appreciate confirmation):
Am I understanding Yehuda's code correctly? (i.e., he really is storing DOM nodes using .attr() right?)
What's the difference between .attr() and .data()? Is it simply that .attr() stores the information in the DOM itself while .data() stores it in a jQuery data hash outside the DOM? (I see that in the documentation for jQuery.data() it says "The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks." perhaps therein lies the rub.)
Are there any other limits of using .attr() that I should be aware of?
When do you choose to use .data() over .attr()? Is it mostly an aesthetic choice, as long as you make sure to use .data() in cases when there could be circular references? Or is one significantly faster?
If you just need a simple flag or number on a DOM node you can use either attr("x_mycount", 1) or just set a property on the DOM node using this.x_mycount instead. (Be careful choosing the attribute or property name since you're in the DOM namespace and you could clobber something if you're not careful.) It's safest to use .data() though.