JQuery Datalink - Data Binding
I was testing Microsoft's jQuery Data Binding Suggestion and noticed something strange.
My objects get this additional property and I was wondering what the reason is for. At first I thought it was a mistake I made, but I noticed that their demo page does the same thing.
This is the json output of my objects:
[{
"propertyName":"ProductNamese",
"controlType":"Text",
"jQuery1274021322131":6
},
{
"propertyName":"Price",
"controlType":"Number",
"jQuery1274021322131":9
},
{
"propertyName":"Description",
"controlType":"TextArea",
"jQuery1274021322131":12
}
]
The property I'm talking about is "jQuery1274021322131".
a source to share
When you pass a DOM object to a jQuery object (ie $("#SomeElementID")
), jQuery adds a special "expando" property to the object. I believe this property is used internally by the library to aid in caching the element in the internal array for faster access.
Digging into the library, this is the code that creates this value and how it is 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
a source to share
jQuery uses expando to bind an object (dom element or otherwise) to its data cache when using the data () method (this is NOT caused by simply running $ () on it as the accepted answer points out), the data binding plugin uses data () for the object thus creating an extension. It's unfortunate that expando is so "regular" that it's easier to hide. For example, it should be encapsulated by a function so that JSON serializers don't include it. jQuery works with regular objects, but there are some rough edges like this. Hopefully they can be ironed out in the future.
a source to share