Hide metadata when serializing JS objects using JSON.stringify via a toJSON hack...
[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 = function () {
72                                 return undefined;
73                         };
74                 }
75
76                 // An object can be passed to jQuery.data instead of a key/value pair; this gets
77                 // shallow copied over onto the existing cache
78                 if ( typeof name === "object" || typeof name === "function" ) {
79                         if ( pvt ) {
80                                 cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
81                         } else {
82                                 cache[ id ] = jQuery.extend(cache[ id ], name);
83                         }
84                 }
85
86                 thisCache = cache[ id ];
87
88                 // Internal jQuery data is stored in a separate object inside the object's data
89                 // cache in order to avoid key collisions between internal data and user-defined
90                 // data
91                 if ( pvt ) {
92                         if ( !thisCache[ internalKey ] ) {
93                                 thisCache[ internalKey ] = {};
94                         }
95
96                         thisCache = thisCache[ internalKey ];
97                 }
98
99                 if ( data !== undefined ) {
100                         thisCache[ name ] = data;
101                 }
102
103                 // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
104                 // not attempt to inspect the internal events object using jQuery.data, as this
105                 // internal data object is undocumented and subject to change.
106                 if ( name === "events" && !thisCache[name] ) {
107                         return thisCache[ internalKey ] && thisCache[ internalKey ].events;
108                 }
109
110                 return getByName ? thisCache[ name ] : thisCache;
111         },
112
113         removeData: function( elem, name, pvt /* Internal Use Only */ ) {
114                 if ( !jQuery.acceptData( elem ) ) {
115                         return;
116                 }
117
118                 var internalKey = jQuery.expando, isNode = elem.nodeType,
119
120                         // See jQuery.data for more information
121                         cache = isNode ? jQuery.cache : elem,
122
123                         // See jQuery.data for more information
124                         id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
125
126                 // If there is already no cache entry for this object, there is no
127                 // purpose in continuing
128                 if ( !cache[ id ] ) {
129                         return;
130                 }
131
132                 if ( name ) {
133                         var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
134
135                         if ( thisCache ) {
136                                 delete thisCache[ name ];
137
138                                 // If there is no data left in the cache, we want to continue
139                                 // and let the cache object itself get destroyed
140                                 if ( !isEmptyDataObject(thisCache) ) {
141                                         return;
142                                 }
143                         }
144                 }
145
146                 // See jQuery.data for more information
147                 if ( pvt ) {
148                         delete cache[ id ][ internalKey ];
149
150                         // Don't destroy the parent cache unless the internal data object
151                         // had been the only thing left in it
152                         if ( !isEmptyDataObject(cache[ id ]) ) {
153                                 return;
154                         }
155                 }
156
157                 var internalCache = cache[ id ][ internalKey ];
158
159                 // Browsers that fail expando deletion also refuse to delete expandos on
160                 // the window, but it will allow it on all other JS objects; other browsers
161                 // don't care
162                 if ( jQuery.support.deleteExpando || cache != window ) {
163                         delete cache[ id ];
164                 } else {
165                         cache[ id ] = null;
166                 }
167
168                 // We destroyed the entire user cache at once because it's faster than
169                 // iterating through each key, but we need to continue to persist internal
170                 // data if it existed
171                 if ( internalCache ) {
172                         cache[ id ] = {};
173                         cache[ id ][ internalKey ] = internalCache;
174
175                 // Otherwise, we need to eliminate the expando on the node to avoid
176                 // false lookups in the cache for entries that no longer exist
177                 } else if ( isNode ) {
178                         // IE does not allow us to delete expando properties from nodes,
179                         // nor does it have a removeAttribute function on Document nodes;
180                         // we must handle all of these cases
181                         if ( jQuery.support.deleteExpando ) {
182                                 delete elem[ jQuery.expando ];
183                         } else if ( elem.removeAttribute ) {
184                                 elem.removeAttribute( jQuery.expando );
185                         } else {
186                                 elem[ jQuery.expando ] = null;
187                         }
188                 }
189         },
190
191         // For internal use only.
192         _data: function( elem, name, data ) {
193                 return jQuery.data( elem, name, data, true );
194         },
195
196         // A method for determining if a DOM node can handle the data expando
197         acceptData: function( elem ) {
198                 if ( elem.nodeName ) {
199                         var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
200
201                         if ( match ) {
202                                 return !(match === true || elem.getAttribute("classid") !== match);
203                         }
204                 }
205
206                 return true;
207         }
208 });
209
210 jQuery.fn.extend({
211         data: function( key, value ) {
212                 var data = null;
213
214                 if ( typeof key === "undefined" ) {
215                         if ( this.length ) {
216                                 data = jQuery.data( this[0] );
217
218                                 if ( this[0].nodeType === 1 ) {
219                                         var attr = this[0].attributes, name;
220                                         for ( var i = 0, l = attr.length; i < l; i++ ) {
221                                                 name = attr[i].name;
222
223                                                 if ( name.indexOf( "data-" ) === 0 ) {
224                                                         name = name.substr( 5 );
225                                                         dataAttr( this[0], name, data[ name ] );
226                                                 }
227                                         }
228                                 }
229                         }
230
231                         return data;
232
233                 } else if ( typeof key === "object" ) {
234                         return this.each(function() {
235                                 jQuery.data( this, key );
236                         });
237                 }
238
239                 var parts = key.split(".");
240                 parts[1] = parts[1] ? "." + parts[1] : "";
241
242                 if ( value === undefined ) {
243                         data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
244
245                         // Try to fetch any internally stored data first
246                         if ( data === undefined && this.length ) {
247                                 data = jQuery.data( this[0], key );
248                                 data = dataAttr( this[0], key, data );
249                         }
250
251                         return data === undefined && parts[1] ?
252                                 this.data( parts[0] ) :
253                                 data;
254
255                 } else {
256                         return this.each(function() {
257                                 var $this = jQuery( this ),
258                                         args = [ parts[0], value ];
259
260                                 $this.triggerHandler( "setData" + parts[1] + "!", args );
261                                 jQuery.data( this, key, value );
262                                 $this.triggerHandler( "changeData" + parts[1] + "!", args );
263                         });
264                 }
265         },
266
267         removeData: function( key ) {
268                 return this.each(function() {
269                         jQuery.removeData( this, key );
270                 });
271         }
272 });
273
274 function dataAttr( elem, key, data ) {
275         // If nothing was found internally, try to fetch any
276         // data from the HTML5 data-* attribute
277         if ( data === undefined && elem.nodeType === 1 ) {
278                 data = elem.getAttribute( "data-" + key );
279
280                 if ( typeof data === "string" ) {
281                         try {
282                                 data = data === "true" ? true :
283                                 data === "false" ? false :
284                                 data === "null" ? null :
285                                 !jQuery.isNaN( data ) ? parseFloat( data ) :
286                                         rbrace.test( data ) ? jQuery.parseJSON( data ) :
287                                         data;
288                         } catch( e ) {}
289
290                         // Make sure we set the data so it isn't changed later
291                         jQuery.data( elem, key, data );
292
293                 } else {
294                         data = undefined;
295                 }
296         }
297
298         return data;
299 }
300
301 // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
302 // property to be considered empty objects; this property always exists in
303 // order to make sure JSON.stringify does not expose internal metadata
304 function isEmptyDataObject( obj ) {
305         for ( var name in obj ) {
306                 if ( name !== "toJSON" ) {
307                         return false;
308                 }
309         }
310
311         return true;
312 }
313
314 })( jQuery );