Where is jQuery.data() stored?

三世轮回 提交于 2019-11-26 09:46:59

问题


Where does jQuery store the values of the data() that it sets to DOM objects?

Is there some kind of variable like jQuery.dataDb or something, maybe even something private?

Is there any way to gain access to this object?


回答1:


Internally, jQuery creates an empty object called $.cache, which is used to store the values you set via the data method. Each DOM element you add data to, is assigned a unique ID which is used as a key in the $.cache object.




回答2:


jQuery gets or sets data in 3 different ways for 3 different type of object.

For DOM element, jQuery first get a unique id, than create a custom property for element called expando:

var counter = 0;
function uid() {
    // only example
    return 'jQuery' + counter;
}
function getExpando(element) {
    var expando = element['jQueryExpando'];
    // for those without expando, create one
    if (!expando) {
        expando = element['jQueryExpando'] = uid();
    }
    return expando;
}

On the other hand, jQuery has a $.cache object which stores data map for each element, jQuery searches $.cache by expando and get a data map for certain element, getting or setting data in that map:

function data(element, name, value) {
    var expando = getExpando(element);
    var map = $.cache[expando];

    // get data
    if (value === undefined) {
        return map && map[name];
    }
    // set data
    else {
        // for those without any data, create a pure map
        if (!map) {
            map = $.cache[expando] = {};
        }
        map[name] = value;
        return value;
    }
}

For custom object(which is not DOM element or window object), jQuery directly set or get a property from that object by name:

function data(obj, name, value) {
    if (!obj) {
        return obj;
    }
    // get data
    if (value === undefined) {
        return obj[name];
    }
    // set data
    else {
        obj[name] = value;
        return value;
    }
}

At last, for the special window object, jQuery has a special windowData variable in closure to store data for window:

function data(obj, name, value) {
    if ($.isWindow(obj)) {
        obj = windowData;
    }
    // same as data for custom object
}



回答3:


Ok I figured it out.

jQuery.expando contains a string that's appended to each element which is jQuery + new Date()

HTMLElement[jQuery.expando] contains the key to that element's data

jQuery.cache[HTMLElement[$.expando]] contains the data on the element

Here is a demo



来源:https://stackoverflow.com/questions/5821520/where-is-jquery-data-stored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!