How to bind data with jQuery object?

I have a jQuery object $myObjectthat contains elements el_1, el_2, ..., el_n. Performance

$myObject.data('foo', 'bar');

assigns a value 'bar'to the data property foofor each item el_1, el_2, ..., el_n. Instead, I would like to associate the data with the jQuery object $myObjectas a single object.

I think I could do

$myObject['foo'] = 'bar';

but this can lead to collisions with other properties and methods of the jQuery object. Is there a jQuery-safe way to bind data to a jQuery object?

+5
source share
2 answers

You can save this data in your own object using jQuery object references as keys, and then save this object in the document data. Sort of:

$.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;
};

, :

$myObject.objData("foo", "bar");

:

var foo = $myObject.objData("foo");

, $myObject , jQuery, , - .

, jQuery, , . jQuery .

+2

.

containerObj = {jquery: $myObject, data: ['data']};
+2

All Articles