Merge branch 'master' of git://github.com/jquery/jquery into fixedbuild
[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                         if ( !isNode ) {
72                                 cache[ id ].toJSON = jQuery.noop;
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                         // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
174                         // metadata on plain JS objects when the object is serialized using
175                         // JSON.stringify
176                         if ( !isNode ) {
177                                 cache[ id ].toJSON = jQuery.noop;
178                         }
179
180                         cache[ id ][ internalKey ] = internalCache;
181
182                 // Otherwise, we need to eliminate the expando on the node to avoid
183                 // false lookups in the cache for entries that no longer exist
184                 } else if ( isNode ) {
185                         // IE does not allow us to delete expando properties from nodes,
186                         // nor does it have a removeAttribute function on Document nodes;
187                         // we must handle all of these cases
188                         if ( jQuery.support.deleteExpando ) {
189                                 delete elem[ jQuery.expando ];
190                         } else if ( elem.removeAttribute ) {
191                                 elem.removeAttribute( jQuery.expando );
192                         } else {
193                                 elem[ jQuery.expando ] = null;
194                         }
195                 }
196         },
197
198         // For internal use only.
199         _data: function( elem, name, data ) {
200                 return jQuery.data( elem, name, data, true );
201         },
202
203         // A method for determining if a DOM node can handle the data expando
204         acceptData: function( elem ) {
205                 if ( elem.nodeName ) {
206                         var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
207
208                         if ( match ) {
209                                 return !(match === true || elem.getAttribute("classid") !== match);
210                         }
211                 }
212
213                 return true;
214         }
215 });
216
217 jQuery.fn.extend({
218         data: function( key, value ) {
219                 var data = null;
220
221                 if ( typeof key === "undefined" ) {
222                         if ( this.length ) {
223                                 data = jQuery.data( this[0] );
224
225                                 if ( this[0].nodeType === 1 ) {
226                                         var attr = this[0].attributes, name;
227                                         for ( var i = 0, l = attr.length; i < l; i++ ) {
228                                                 name = attr[i].name;
229
230                                                 if ( name.indexOf( "data-" ) === 0 ) {
231                                                         name = name.substr( 5 );
232                                                         dataAttr( this[0], name, data[ name ] );
233                                                 }
234                                         }
235                                 }
236                         }
237
238                         return data;
239
240                 } else if ( typeof key === "object" ) {
241                         return this.each(function() {
242                                 jQuery.data( this, key );
243                         });
244                 }
245
246                 var parts = key.split(".");
247                 parts[1] = parts[1] ? "." + parts[1] : "";
248
249                 if ( value === undefined ) {
250                         data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
251
252                         // Try to fetch any internally stored data first
253                         if ( data === undefined && this.length ) {
254                                 data = jQuery.data( this[0], key );
255                                 data = dataAttr( this[0], key, data );
256                         }
257
258                         return data === undefined && parts[1] ?
259                                 this.data( parts[0] ) :
260                                 data;
261
262                 } else {
263                         return this.each(function() {
264                                 var $this = jQuery( this ),
265                                         args = [ parts[0], value ];
266
267                                 $this.triggerHandler( "setData" + parts[1] + "!", args );
268                                 jQuery.data( this, key, value );
269                                 $this.triggerHandler( "changeData" + parts[1] + "!", args );
270                         });
271                 }
272         },
273
274         removeData: function( key ) {
275                 return this.each(function() {
276                         jQuery.removeData( this, key );
277                 });
278         }
279 });
280
281 function dataAttr( elem, key, data ) {
282         // If nothing was found internally, try to fetch any
283         // data from the HTML5 data-* attribute
284         if ( data === undefined && elem.nodeType === 1 ) {
285                 data = elem.getAttribute( "data-" + key );
286
287                 if ( typeof data === "string" ) {
288                         try {
289                                 data = data === "true" ? true :
290                                 data === "false" ? false :
291                                 data === "null" ? null :
292                                 !jQuery.isNaN( data ) ? parseFloat( data ) :
293                                         rbrace.test( data ) ? jQuery.parseJSON( data ) :
294                                         data;
295                         } catch( e ) {}
296
297                         // Make sure we set the data so it isn't changed later
298                         jQuery.data( elem, key, data );
299
300                 } else {
301                         data = undefined;
302                 }
303         }
304
305         return data;
306 }
307
308 // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
309 // property to be considered empty objects; this property always exists in
310 // order to make sure JSON.stringify does not expose internal metadata
311 function isEmptyDataObject( obj ) {
312         for ( var name in obj ) {
313                 if ( name !== "toJSON" ) {
314                         return false;
315                 }
316         }
317
318         return true;
319 }
320
321 })( jQuery );