Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to associate data to a jQuery object?

Tags:

jquery

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?

like image 921
Randomblue Avatar asked Oct 10 '22 18:10

Randomblue


1 Answers

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.

like image 140
Frédéric Hamidi Avatar answered Oct 13 '22 12:10

Frédéric Hamidi