Fix bug when accessing .data() on an empty set. Return null rather than throwing...
[jquery.git] / src / data.js
index dda1683..b7a6ab9 100644 (file)
@@ -1,7 +1,8 @@
 (function( jQuery ) {
 
 var windowData = {},
-       rnum = /^-?\d+(?:\.\d+)$/;
+       rbrace = /^(?:\{.*\}|\[.*\])$/,
+       rdigit = /\d/;
 
 jQuery.extend({
        cache: {},
@@ -128,8 +129,8 @@ jQuery.extend({
 
 jQuery.fn.extend({
        data: function( key, value ) {
-               if ( typeof key === "undefined" && this.length ) {
-                       return jQuery.data( this[0] );
+               if ( typeof key === "undefined" ) {
+                       return this.length ? jQuery.data( this[0] ) : null;
 
                } else if ( typeof key === "object" ) {
                        return this.each(function() {
@@ -153,11 +154,14 @@ jQuery.fn.extend({
                                        data = this[0].getAttribute( "data-" + key );
 
                                        if ( typeof data === "string" ) {
-                                               data = data === "true" ? true :
-                                                       data === "false" ? false :
-                                                       data === "null" ? null :
-                                                       rnum.test( data ) ? parseFloat( data ) :
-                                                       data;
+                                               try {
+                                                       data = data === "true" ? true :
+                                                               data === "false" ? false :
+                                                               data === "null" ? null :
+                                                               rdigit.test( data ) && !isNaN( data ) ? parseFloat( data ) :
+                                                               rbrace.test( data ) ? jQuery.parseJSON( data ) :
+                                                               data;
+                                               } catch( e ) {}
 
                                        } else {
                                                data = undefined;