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:
$.fn.objData = function(key, value) {
var rootData = $(document).data("jQueryObjectData");
if (!rootData) {
$(document).data("jQueryObjectData", rootData = {});
}
var objData = rootData[this];
if (!objData) {
rootData[this] = objData = {};
}
if (typeof value === "undefined") {
return objData[key];
}
objData[key] = value;
return this;
};
Then you can use the method as expected:
$myObject.objData("foo", "bar");
And later:
var foo = $myObject.objData("foo");
Of course, $myObject
must 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With