开发者

jQuery Datalink - Data linking

开发者 https://www.devze.com 2022-12-31 00:24 出处:网络
I was trying out the jQuery Data linking proposal from Microsoftand noticed something strange. My objects get this extra property and I was wondering what the reason for that is. I first thought it w

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.

0

上一篇:

:下一篇

精彩评论

暂无评论...
验证码 换一张
取 消