views:

40

answers:

1

Hello,

Is it possible and smart to store extra data inside a jQuery object?

Right now I have objects that contain some data but these objects also have a visual representation of that data. This works but I have a lot of code to keep them both in sync.

For example if you delete an object from the dom I also have to delete the related object from the object array. Deleting is fairly simple but it gets a little more complicated if I start sorting/moving the objects around.

+8  A: 

You can use $.data() for this :)

For example:

$.data(element, 'varName', value);      //store
var value = $.data(element, 'varName'); //get

Or use the object method .data():

$("#ElementID").data('varName', value);      //store
var value = $("#ElementID").data('varName'); //get

This doesn't store the data on the object, rather it stores it in $.cache (try it in your console on this page), but it's associated with the object, via this[$.expando].

However if you call .empty() that removes an object, or .remove(), it'll do the cleanup for you. You can also call .removeData() or $.removeData() to remove it directly.

Nick Craver
Wow, that's perfect. Thanks for the answer.
Pickels
@Pickels - Welcome :) I added a few more methods at the end you may be interested in, since you're managing the objects directly (at least that's my take from the question).
Nick Craver
I thought I read about cache before so that got me wondering in the first place if it was possible to store related data. Thanks for the extra methods this will make my code a lot less complex.
Pickels