What's the difference between jQuery.data and jQuery._data ( underscore data )?

前端 未结 1 946
一个人的身影
一个人的身影 2020-12-08 07:23

While going through the source, I noticed that \'toggle\' supposedly uses jQuery._data to store the state of the element. I examined the jQuery.cache

相关标签:
1条回答
  • 2020-12-08 07:53

    jQuery uses _data in order to set the 'pvt' flag for data it stores on the object. The pvt is used so that when you request public data from the object, pvt data is not returned. This is to keep jQuery's internal use of the .data() mechanism (like what toggle does) from effecting the public use of .data().

    You can see this declaration in the jQuery source:

    // For internal use only.
    _data: function( elem, name, data ) {
        return jQuery.data( elem, name, data, true );
    },
    

    Which just calls jQuery.data and forces the fourth parameter (which is privacy) to be true. When retrieving data, if the pvt flag is set, then it is retrieved in a slightly different way. The public interfaces to .data() do not expose the pvt flag.

    You can see an example of pvt handling here in this part of jQuery.data():

    // An object can be passed to jQuery.data instead of a key/value pair; this gets
    // shallow copied over onto the existing cache
    if ( typeof name === "object" || typeof name === "function" ) {
        if ( pvt ) {
            cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
        } else {
            cache[ id ] = jQuery.extend(cache[ id ], name);
        }
    }
    

    and then later in that same function, this comment is pretty descriptive:

    // Internal jQuery data is stored in a separate object inside the object's data
    // cache in order to avoid key collisions between internal data and user-defined
    // data
    if ( pvt ) {
        if ( !thisCache[ internalKey ] ) {
            thisCache[ internalKey ] = {};
        }
        thisCache = thisCache[ internalKey ];
    }
    
    0 讨论(0)
提交回复
热议问题