jQuery Datalink - Data linking
I was trying out the jQuery Data linking proposal from Microsoft and noticed something strange.
My objects get this extra property and I was wondering what the reason for that is. I first thought it was a mistake I made but I noticed their demo page does the same thing
This is the json result of my objects:
[{
"propertyName":"ProductNamese",
"controlType":"Text",
"jQuery1274021322131":6
},
{
"p开发者_如何学编程ropertyName":"Price",
"controlType":"Number",
"jQuery1274021322131":9
},
{
"propertyName":"Description",
"controlType":"TextArea",
"jQuery1274021322131":12
}
]
The property I am talking about is "jQuery1274021322131".
When you cast an DOM object to a jQuery object (i.e. $("#SomeElementID")
), jQuery appends a special "expando" property to the object. I believe that this property is used internally by the library to assist in caching the element in its internal array for faster access.
Digging through the library, this is the code that creates that value and how it's used internally:
var expando = "jQuery" + now(), uuid = 0, windowData = {};
jQuery.extend({
cache: {},
data: function( elem, name, data ) {
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ];
// Compute a unique ID for the element
if ( !id )
id = elem[ expando ] = ++uuid;
// Only generate the data cache if we're
// trying to access or manipulate it
if ( name && !jQuery.cache[ id ] )
jQuery.cache[ id ] = {};
// Prevent overriding the named cache with undefined values
if ( data !== undefined )
jQuery.cache[ id ][ name ] = data;
// Return the named cache data, or the ID for the element
return name ?
jQuery.cache[ id ][ name ] :
id;
},
// snipped
jQuery uses the expando to associate an object (dom element, or otherwise) with it's cache of data when using the data() method (it is NOT caused by simply running $() on it, as the accepted answer specifies). The data linking plugin uses data() on the object, thus creating the expando. It's unfortunate that the expando is so 'regular' -- it should be more easily hidden. For example, it should be encapulated a function so that JSON serializers don't include it. jQuery works with regular objects, but there are some rough edges like this one. Hopefully they can be ironed out in the future.
精彩评论