I have a jQuery object $myObject that contains the elements el_1, el_2, ..., el_n. Doing
$myObject.data('foo', 'bar');
will assign the value 'bar' to the data property foo for each element el_1, el_2, ..., el_n. Instead, I would like to associate data to the jQuery object $myObject as a single entity.
I guess I could do
$myObject['foo'] = 'bar';
but this may cause collisions with other properties and methods of the jQuery object. Is there a “jQuery-safe way” to associate data with a jQuery object?
You can store that data in your own object, using the jQuery object references as keys, then store that object in the document’s data. Something like:
Then you can use the method as expected:
And later:
Of course,
$myObjectmust refer to the very same object in the two calls, as two distinct jQuery objects containing the same elements will still count as different keys.A potential problem with this approach is that the root data object will keep a reference to the jQuery objects used as keys, thus preventing the garbage collector from disposing them. It might prove to be a issue depending on the number of jQuery objects you create and the way you use the method.