Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery data() storage

Can any one tell me where jquery data() stores the data and when it is get erased and how?

Is there any performance issue if I use this to store ajax call result?

For example:

$("body").data("test", { myData: 'abcd'});
like image 381
ANP Avatar asked Dec 08 '10 06:12

ANP


2 Answers

All data is stored inside a property of the jQuery object named cache. Log the contents of $.cache in your console to see all data and events associated with any DOM element.

The way jQuery links up a DOM object with an object in this cache is by manipulating the DOM object. Say we have a input element

<input type="text" value="hello" />

which has a data key named "foo"

$(e).data("foo", "bar");

Now jQuery maintains a random string of the form jQuery<current time in ms>, for example, jQuery1291790929680, which is also accessible by $.expando. jQuery adds this expando string as a key to each DOM object that has an associated data item or event. So the DOM object for the above input element will contain this expando key with some integer value such as:

jQuery1291790929680: 4

4 is just a random example, but this number denotes an index in the $.cache object, where the associated data and events for this DOM object are stored. So given this information, to retrieve the data of the above input element, we can indirectly write:

$.cache[4]["foo"]

which should return "bar", which is an indirect way of writing $(e).data("foo").

An illustrated example of the above nonsense :)

like image 69
Anurag Avatar answered Nov 03 '22 09:11

Anurag


see the content from jquery

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 free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page. We can set several distinct values for a single element and retrieve them later:

like image 25
kobe Avatar answered Nov 03 '22 08:11

kobe