Posts Tagged ‘data’

Using jQuery.data() function to store data associated with the element

Monday, June 22nd, 2009

One easy way to store element specific data is to use the attribute of HTML element like below.

$(“div#ID”).attr(“data”, “id:3”)

This works. But it doesn’s seem very nice for some reasons. First, it uses ‘data’ attribute, which is not valid XHTML. It contaminates HTML document. Second, it is hard to parse data. More complicate data, harder to parse. You can use json string as data to ease parsing, but eval operation is expensive.

There is an absolutely better way if you’re using jquery. data function.

// save
var user = {id:3, name='clever'}
$(“div#ID”).data(“user”, user)
// get
user = $(“div#ID”).data(“user”)
// delete
$(“div#ID”).removeData(“user”)

This is much easier to understand and fast. Moreover, firebug does not show any of data, cause it does not use any HTML attributes. How nice! Actually, it uses internal cache to store data.

Lets’s inspect jquery source codes to understand how jQuery.data works. All data is stored in jQuery.cache. Element can access its data using cache_id, which is just increasing number. The Element only stores this cache_id with the name of ‘jQuery’ + Timestamp. So the process to find element’s data is like below.

  1. Find cache_id of the element.
  2. Find data in cache using cache_id

One nice additional feature using jQuery.data is queue. You can queue and dequeue jobs like below.

$("div#ID").queue("msg", function() { alert("progressing");});
$("div#ID").queue("msg", function() { alert("Done");});
// In worker
$("div#ID").queue("msg");