Associating data with DOM elements
Let's say you create a div element for each enemy in your game. You will probably want to associate them to some numerical value, like their life. You may even want to associate an object if you're writing object-oriented code.
jQuery provides a simple method to do this, that is, .data()
. This method takes a key and a value. If you later call it with only the key, it will return the value. For example, the following code associates the numerical value 3
with the key "numberOfLife"
for the element with ID enemy3
.
$("#enemy3").data("numberOfLife", 3);
You may be thinking, "Why shouldn't I simply store my values directly on the DOM element?". There is a very good answer for that. By using .data()
, you completely decouple your value and the DOM, which will make it way easier to avoid a situation where the garbage collector doesn't free the memory associated with the DOM of a removed element because you're still holding some cyclic reference to it somewhere.
If you defined some values using the HTML5 data attribute (http://ejohn.org/blog/html-5-data-attributes/), the .data()
function retrieves them too.
However, you have to keep in mind that making calls to this function has some performance cost, and if you have many values to store for an element, you may want to store all of them in an object literal associated with a single key instead of many values, each associated with their own key.