Update jQuery.data to use jQuery.noop for toJSON hack instead of an additional superf...
[jquery.git] / src / data.js
1 (function( jQuery ) {
2
3 var rbrace = /^(?:\{.*\}|\[.*\])$/;
4
5 jQuery.extend({
6         cache: {},
7
8         // Please use with caution
9         uuid: 0,
10
11         // Unique for each copy of jQuery on the page
12         // Non-digits removed to match rinlinejQuery
13         expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
14
15         // The following elements throw uncatchable exceptions if you
16         // attempt to add expando properties to them.
17         noData: {
18                 "embed": true,
19                 // Ban all objects except for Flash (which handle expandos)
20                 "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
21                 "applet": true
22         },
23
24         hasData: function( elem ) {
25                 elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
26
27                 return !!elem && !isEmptyDataObject( elem );
28         },
29
30         data: function( elem, name, data, pvt /* Internal Use Only */ ) {
31                 if ( !jQuery.acceptData( elem ) ) {
32                         return;
33                 }
34
35                 var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
36
37                         // We have to handle DOM nodes and JS objects differently because IE6-7
38                         // can't GC object references properly across the DOM-JS boundary
39                         isNode = elem.nodeType,
40
41                         // Only DOM nodes need the global jQuery cache; JS object data is
42                         // attached directly to the object so GC can occur automatically
43                         cache = isNode ? jQuery.cache : elem,
44
45                         // Only defining an ID for JS objects if its cache already exists allows
46                         // the code to shortcut on the same path as a DOM node with no cache
47                         id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
48
49                 // Avoid doing any more work than we need to when trying to get data on an
50                 // object that has no data at all
51                 if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
52                         return;
53                 }
54
55                 if ( !id ) {
56                         // Only DOM nodes need a new unique ID for each element since their data
57                         // ends up in the global cache
58                         if ( isNode ) {
59                                 elem[ jQuery.expando ] = id = ++jQuery.uuid;
60                         } else {
61                                 id = jQuery.expando;
62                         }
63                 }
64
65                 if ( !cache[ id ] ) {
66                         cache[ id ] = {};
67
68                         // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
69                         // metadata on plain JS objects when the object is serialized using
70                         // JSON.stringify
71                         cache[ id ].toJSON = jQuery.noop;
72                 }
73
74                 // An object can be passed to jQuery.data instead of a key/value pair; this gets
75                 // shallow copied over onto the existing cache
76                 if ( typeof name === "object" || typeof name === "function" ) {
77                         if ( pvt ) {
78                                 cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
79                         } else {
80                                 cache[ id ] = jQuery.extend(cache[ id ], name);
81                         }
82                 }
83
84                 thisCache = cache[ id ];
85
86                 // Internal jQuery data is stored in a separate object inside the object's data
87                 // cache in order to avoid key collisions between internal data and user-defined
88                 // data
89                 if ( pvt ) {
90                         if ( !thisCache[ internalKey ] ) {
91                                 thisCache[ internalKey ] = {};
92                         }
93
94                         thisCache = thisCache[ internalKey ];
95                 }
96
97                 if ( data !== undefined ) {
98                         thisCache[ name ] = data;
99                 }
100
101                 // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
102                 // not attempt to inspect the internal events object using jQuery.data, as this
103                 // internal data object is undocumented and subject to change.
104                 if ( name === "events" && !thisCache[name] ) {
105                         return thisCache[ internalKey ] && thisCache[ internalKey ].events;
106                 }
107
108                 return getByName ? thisCache[ name ] : thisCache;
109         },
110
111         removeData: function( elem, name, pvt /* Internal Use Only */ ) {
112                 if ( !jQuery.acceptData( elem ) ) {
113                         return;
114                 }
115
116                 var internalKey = jQuery.expando, isNode = elem.nodeType,
117
118                         // See jQuery.data for more information
119                         cache = isNode ? jQuery.cache : elem,
120
121                         // See jQuery.data for more information
122                         id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
123
124                 // If there is already no cache entry for this object, there is no
125                 // purpose in continuing
126                 if ( !cache[ id ] ) {
127                         return;
128                 }
129
130                 if ( name ) {
131                         var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
132
133                         if ( thisCache ) {
134                                 delete thisCache[ name ];
135
136                                 // If there is no data left in the cache, we want to continue
137                                 // and let the cache object itself get destroyed
138                                 if ( !isEmptyDataObject(thisCache) ) {
139                                         return;
140                                 }
141                         }
142                 }
143
144                 // See jQuery.data for more information
145                 if ( pvt ) {
146                         delete cache[ id ][ internalKey ];
147
148                         // Don't destroy the parent cache unless the internal data object
149                         // had been the only thing left in it
150                         if ( !isEmptyDataObject(cache[ id ]) ) {
151                                 return;
152                         }
153                 }
154
155                 var internalCache = cache[ id ][ internalKey ];
156
157                 // Browsers that fail expando deletion also refuse to delete expandos on
158                 // the window, but it will allow it on all other JS objects; other browsers
159                 // don't care
160                 if ( jQuery.support.deleteExpando || cache != window ) {
161                         delete cache[ id ];
162                 } else {
163                         cache[ id ] = null;
164                 }
165
166                 // We destroyed the entire user cache at once because it's faster than
167                 // iterating through each key, but we need to continue to persist internal
168                 // data if it existed
169                 if ( internalCache ) {
170                         cache[ id ] = {};
171                         cache[ id ][ internalKey ] = internalCache;
172
173                 // Otherwise, we need to eliminate the expando on the node to avoid
174                 // false lookups in the cache for entries that no longer exist
175                 } else if ( isNode ) {
176                         // IE does not allow us to delete expando properties from nodes,
177                         // nor does it have a removeAttribute function on Document nodes;
178                         // we must handle all of these cases
179                         if ( jQuery.support.deleteExpando ) {
180                                 delete elem[ jQuery.expando ];
181                         } else if ( elem.removeAttribute ) {
182                                 elem.removeAttribute( jQuery.expando );
183                         } else {
184                                 elem[ jQuery.expando ] = null;
185                         }
186                 }
187         },
188
189         // For internal use only.
190         _data: function( elem, name, data ) {
191                 return jQuery.data( elem, name, data, true );
192         },
193
194         // A method for determining if a DOM node can handle the data expando
195         acceptData: function( elem ) {
196                 if ( elem.nodeName ) {
197                         var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
198
199                         if ( match ) {
200                                 return !(match === true || elem.getAttribute("classid") !== match);
201                         }
202                 }
203
204                 return true;
205         }
206 });
207
208 jQuery.fn.extend({
209         data: function( key, value ) {
210                 var data = null;
211
212                 if ( typeof key === "undefined" ) {
213                         if ( this.length ) {
214                                 data = jQuery.data( this[0] );
215
216                                 if ( this[0].nodeType === 1 ) {
217                                         var attr = this[0].attributes, name;
218                                         for ( var i = 0, l = attr.length; i < l; i++ ) {
219                                                 name = attr[i].name;
220
221                                                 if ( name.indexOf( "data-" ) === 0 ) {
222                                                         name = name.substr( 5 );
223                                                         dataAttr( this[0], name, data[ name ] );
224                                                 }
225                                         }
226                                 }
227                         }
228
229                         return data;
230
231                 } else if ( typeof key === "object" ) {
232                         return this.each(function() {
233                                 jQuery.data( this, key );
234                         });
235                 }
236
237                 var parts = key.split(".");
238                 parts[1] = parts[1] ? "." + parts[1] : "";
239
240                 if ( value === undefined ) {
241                         data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
242
243                         // Try to fetch any internally stored data first
244                         if ( data === undefined && this.length ) {
245                                 data = jQuery.data( this[0], key );
246                                 data = dataAttr( this[0], key, data );
247                         }
248
249                         return data === undefined && parts[1] ?
250                                 this.data( parts[0] ) :
251                                 data;
252
253                 } else {
254                         return this.each(function() {
255                                 var $this = jQuery( this ),
256                                         args = [ parts[0], value ];
257
258                                 $this.triggerHandler( "setData" + parts[1] + "!", args );
259                                 jQuery.data( this, key, value );
260                                 $this.triggerHandler( "changeData" + parts[1] + "!", args );
261                         });
262                 }
263         },
264
265         removeData: function( key ) {
266                 return this.each(function() {
267                         jQuery.removeData( this, key );
268                 });
269         }
270 });
271
272 function dataAttr( elem, key, data ) {
273         // If nothing was found internally, try to fetch any
274         // data from the HTML5 data-* attribute
275         if ( data === undefined && elem.nodeType === 1 ) {
276                 data = elem.getAttribute( "data-" + key );
277
278                 if ( typeof data === "string" ) {
279                         try {
280                                 data = data === "true" ? true :
281                                 data === "false" ? false :
282                                 data === "null" ? null :
283                                 !jQuery.isNaN( data ) ? parseFloat( data ) :
284                                         rbrace.test( data ) ? jQuery.parseJSON( data ) :
285                                         data;
286                         } catch( e ) {}
287
288                         // Make sure we set the data so it isn't changed later
289                         jQuery.data( elem, key, data );
290
291                 } else {
292                         data = undefined;
293                 }
294         }
295
296         return data;
297 }
298
299 // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
300 // property to be considered empty objects; this property always exists in
301 // order to make sure JSON.stringify does not expose internal metadata
302 function isEmptyDataObject( obj ) {
303         for ( var name in obj ) {
304                 if ( name !== "toJSON" ) {
305                         return false;
306                 }
307         }
308
309         return true;
310 }
311
312 })( jQuery );