Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

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

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 object in chrome and found that the element's data object had yet another object under it prepended by the word jQuery with a number that I'm guessing uniquely identifies it. However, I saw no data regarding the state of the element. Simply {olddisplay: 'block'}. Any clues as to the purpose of jQuery._data and how it works per se?

I've been staring at the source all day .... please don't tell me to view the source. My eyes and brain will thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...