jQuery: data() and JavaScript objects

jQuery allows us to associate any kind of data even to normal JavaScript objects. This can be achieved thanks to the $() wrapper and the data() method. The interesting thing to note here is that objects are not modified in any way, thus preserving their integrity. For example:

var options = {
  element: 'a',
  speed: 500
};

var Class = {
  property: 'Test'
};

We want to associate the options object to the Class object. Here's how we can do:

$(Class).data('settings', options);

We use the $() wrapper on our target object and then we call data() by setting first the name of our attached object and then its data (that is, our options object). We can access the data object in this way:

var settings = $(Class).data('settings');

alert(settings.element); // alerts 'a'
alert(settings.speed); // alerts 500
alert(Class.element);  // alerts 'undefined'

Since the data() method doesn't modify the original object, the last statement returns undefined, because the specified property is not part of our target object.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: data() and JavaScript objects”

Leave a Reply

Note: Only a member of this blog may post a comment.