From 69a9d03edf78dd720819aea8f603f42b1660d023 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Go=C5=82e=CC=A8biowski-Owczarek?= Date: Mon, 28 Oct 2024 19:07:01 +0100 Subject: [PATCH] Data: Patch camelCase behavior of $.fn.data, warn about Object.prototype Changes: 1. Patch not only `jQuery.data()`, but also `jQuery.fn.data()`. 2. Patch `jQuery.removeData()` & `jQuery.fn.removeData()` to work in most cases when different keys with the same camelCase representation were passed to the data setter and later to `removeData`. 3. Warn about using properties inherited from `Object.prototype` on data objects. --- src/jquery/data.js | 352 ++++++++- test/data/testinit.js | 1 + test/unit/jquery/data-jquery-compat.js | 949 +++++++++++++++++++++++++ test/unit/jquery/data.js | 265 ++++--- warnings.md | 9 + 5 files changed, 1469 insertions(+), 107 deletions(-) create mode 100644 test/unit/jquery/data-jquery-compat.js diff --git a/src/jquery/data.js b/src/jquery/data.js index 07430ce6..20e5c8d7 100644 --- a/src/jquery/data.js +++ b/src/jquery/data.js @@ -1,44 +1,344 @@ import { migratePatchFunc, migrateWarn } from "../main.js"; import { camelCase } from "../utils.js"; -var origData = jQuery.data; +var rmultiDash = /[A-Z]/g, + rnothtmlwhite = /[^\x20\t\r\n\f]+/g, + origJQueryData = jQuery.data; -migratePatchFunc( jQuery, "data", function( elem, name, value ) { - var curData, sameKeys, key; +function unCamelCase( str ) { + return str.replace( rmultiDash, "-$&" ).toLowerCase(); +} - // Name can be an object, and each entry in the object is meant to be set as data - if ( name && typeof name === "object" && arguments.length === 2 ) { +function patchDataCamelCase( origData, options ) { + var apiName = options.apiName, + isInstanceMethod = options.isInstanceMethod; - curData = jQuery.hasData( elem ) && origData.call( this, elem ); - sameKeys = {}; - for ( key in name ) { - if ( key !== camelCase( key ) ) { - migrateWarn( "data-camelCase", - "jQuery.data() always sets/gets camelCased names: " + key ); - curData[ key ] = name[ key ]; + function objectSetter( elem, obj ) { + var curData, key; + + // Name can be an object, and each entry in the object is meant + // to be set as data. + // Let the original method handle the case of a missing elem. + if ( elem ) { + + // Don't use the instance method here to avoid `data-*` attributes + // detection this early. + curData = origJQueryData( elem ); + + for ( key in obj ) { + if ( key !== camelCase( key ) ) { + migrateWarn( "data-camelCase", + apiName + " always sets/gets camelCased names: " + + key ); + curData[ key ] = obj[ key ]; + } + } + + // Pass the keys handled above to the original API as well + // so that both the camelCase & initial keys are saved. + if ( isInstanceMethod ) { + origData.call( this, obj ); } else { - sameKeys[ key ] = name[ key ]; + origData.call( this, elem, obj ); } + + return obj; } + } - origData.call( this, elem, sameKeys ); + function singleSetter( elem, name, value ) { + var curData; - return name; - } + // If the name is transformed, look for the un-transformed name + // in the data object. + // Let the original method handle the case of a missing elem. + if ( elem ) { - // If the name is transformed, look for the un-transformed name in the data object - if ( name && typeof name === "string" && name !== camelCase( name ) ) { + // Don't use the instance method here to avoid `data-*` attributes + // detection this early. + curData = origJQueryData( elem ); + + if ( curData && name in curData ) { + migrateWarn( "data-camelCase", + apiName + " always sets/gets camelCased names: " + + name ); - curData = jQuery.hasData( elem ) && origData.call( this, elem ); - if ( curData && name in curData ) { - migrateWarn( "data-camelCase", - "jQuery.data() always sets/gets camelCased names: " + name ); - if ( arguments.length > 2 ) { curData[ name ] = value; } - return curData[ name ]; + + origJQueryData( elem, name, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken. + return value !== undefined ? value : name; } } - return origData.apply( this, arguments ); -}, "data-camelCase" ); + return function jQueryDataPatched( elem, name, value ) { + var curData, + that = this, + + // Support: IE 9 only + // IE 9 doesn't support strict mode and later modifications of + // parameters also modify the arguments object in sloppy mode. + // We need the original arguments so save them here. + args = Array.prototype.slice.call( arguments ), + + adjustedArgsLength = args.length; + + if ( isInstanceMethod ) { + value = name; + name = elem; + elem = that[ 0 ]; + adjustedArgsLength++; + } + + if ( name && typeof name === "object" && adjustedArgsLength === 2 ) { + if ( isInstanceMethod ) { + return that.each( function() { + objectSetter.call( that, this, name ); + } ); + } else { + return objectSetter.call( that, elem, name ); + } + } + + // If the name is transformed, look for the un-transformed name + // in the data object. + // Let the original method handle the case of a missing elem. + if ( name && typeof name === "string" && name !== camelCase( name ) && + adjustedArgsLength > 2 ) { + + if ( isInstanceMethod ) { + return that.each( function() { + singleSetter.call( that, this, name, value ); + } ); + } else { + return singleSetter.call( that, elem, name, value ); + } + } + + if ( elem && name && typeof name === "string" && + name !== camelCase( name ) && + adjustedArgsLength === 2 ) { + + // Don't use the instance method here to avoid `data-*` attributes + // detection this early. + curData = origJQueryData( elem ); + + if ( curData && name in curData ) { + migrateWarn( "data-camelCase", + apiName + " always sets/gets camelCased names: " + + name ); + return curData[ name ]; + } + } + + return origData.apply( this, args ); + }; +} + +function patchRemoveDataCamelCase( origRemoveData, options ) { + var isInstanceMethod = options.isInstanceMethod; + + function remove( elem, keys ) { + var i, singleKey, unCamelCasedKeys, + curData = jQuery.data( elem ); + + if ( keys === undefined ) { + origRemoveData( elem ); + return; + } + + // Support array or space separated string of keys + if ( !Array.isArray( keys ) ) { + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + keys = keys in curData ? + [ keys ] : + ( keys.match( rnothtmlwhite ) || [] ); + } + + // Remove: + // * the original keys as passed + // * their "unCamelCased" version + // * their camelCase version + // These may be three distinct values for each key! + // jQuery 3.x only removes camelCase versions by default. However, in this patch + // we set the original keys in the mass-setter case and if the key already exists + // so without removing the "unCamelCased" versions the following would be broken: + // ```js + // elem.data( { "a-a": 1 } ).removeData( "aA" ); + // ``` + // Unfortunately, we'll still hit this issue for partially camelCased keys, e.g.: + // ```js + // elem.data( { "a-aA": 1 } ).removeData( "aAA" ); + // ``` + // won't work with this patch. We consider this an edge case, but to make sure that + // at least piggybacking works: + // ```js + // elem.data( { "a-aA": 1 } ).removeData( "a-aA" ); + // ``` + // we also remove the original key. Hence, all three are needed. + // The original API already removes the camelCase versions, though, so let's defer + // to it. + unCamelCasedKeys = keys.map( unCamelCase ); + + i = keys.length; + while ( i-- ) { + singleKey = keys[ i ]; + if ( singleKey !== camelCase( singleKey ) && singleKey in curData ) { + migrateWarn( "data-camelCase", + "jQuery" + ( isInstanceMethod ? ".fn" : "" ) + + ".data() always sets/gets camelCased names: " + + singleKey ); + } + delete curData[ singleKey ]; + } + + // Don't warn when removing "unCamelCased" keys; we're already printing + // a warning when setting them and the fix is needed there, not in + // the `.removeData()` call. + i = unCamelCasedKeys.length; + while ( i-- ) { + delete curData[ unCamelCasedKeys[ i ] ]; + } + + origRemoveData( elem, keys ); + } + + return function jQueryRemoveDataPatched( elem, key ) { + if ( isInstanceMethod ) { + key = elem; + return this.each( function() { + remove( this, key ); + } ); + } else { + remove( elem, key ); + } + }; +} + +migratePatchFunc( jQuery, "data", + patchDataCamelCase( jQuery.data, { + apiName: "jQuery.data()", + isInstanceMethod: false + } ), + "data-camelCase" ); +migratePatchFunc( jQuery.fn, "data", + patchDataCamelCase( jQuery.fn.data, { + apiName: "jQuery.fn.data()", + isInstanceMethod: true + } ), + "data-camelCase" ); + +migratePatchFunc( jQuery, "removeData", + patchRemoveDataCamelCase( jQuery.removeData, { + isInstanceMethod: false + } ), + "data-camelCase" ); + +migratePatchFunc( jQuery.fn, "removeData", + + // No, it's not a typo - we're intentionally passing + // the static method here as we need something working on + // a single element. + patchRemoveDataCamelCase( jQuery.removeData, { + isInstanceMethod: true + } ), + "data-camelCase" ); + + +function patchDataProto( original, options ) { + + // Support: IE 9 - 10 only, iOS 7 - 8 only + // Older IE doesn't have a way to change an existing prototype. + // Just return the original method there. + // Older WebKit supports `__proto__` but not `Object.setPrototypeOf`. + // To avoid complicating code, don't patch the API there either. + if ( !Object.setPrototypeOf ) { + return original; + } + + var i, + apiName = options.apiName, + isInstanceMethod = options.isInstanceMethod, + + // `Object.prototype` keys are not enumerable so list the + // official ones here. An alternative would be wrapping + // data objects with a Proxy but that creates additional issues + // like breaking object identity on subsequent calls. + objProtoKeys = [ + "__proto__", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "toLocaleString", + "toString", + "valueOf" + ], + + // Use a null prototype at the beginning so that we can define our + // `__proto__` getter & setter. We'll reset the prototype afterwards. + intermediateDataObj = Object.create( null ); + + for ( i = 0; i < objProtoKeys.length; i++ ) { + ( function( key ) { + Object.defineProperty( intermediateDataObj, key, { + get: function() { + migrateWarn( "data-null-proto", + "Accessing properties from " + apiName + + " inherited from Object.prototype is deprecated" ); + return ( key + "__cache" ) in intermediateDataObj ? + intermediateDataObj[ key + "__cache" ] : + Object.prototype[ key ]; + }, + set: function( value ) { + migrateWarn( "data-null-proto", + "Setting properties from " + apiName + + " inherited from Object.prototype is deprecated" ); + intermediateDataObj[ key + "__cache" ] = value; + } + } ); + } )( objProtoKeys[ i ] ); + } + + Object.setPrototypeOf( intermediateDataObj, Object.prototype ); + + return function jQueryDataProtoPatched() { + var result = original.apply( this, arguments ); + + if ( arguments.length !== ( isInstanceMethod ? 0 : 1 ) || result === undefined ) { + return result; + } + + // Insert an additional object in the prototype chain between `result` + // and `Object.prototype`; that intermediate object proxies properties + // to `Object.prototype`, warning about their usage first. + Object.setPrototypeOf( result, intermediateDataObj ); + + return result; + }; +} + +// Yes, we are patching jQuery.data twice; here & above. This is necessary +// so that each of the two patches can be independently disabled. +migratePatchFunc( jQuery, "data", + patchDataProto( jQuery.data, { + apiName: "jQuery.data()", + isPrivateData: false, + isInstanceMethod: false + } ), + "data-null-proto" ); +migratePatchFunc( jQuery.fn, "data", + patchDataProto( jQuery.fn.data, { + apiName: "jQuery.fn.data()", + isPrivateData: true, + isInstanceMethod: true + } ), + "data-null-proto" ); diff --git a/test/data/testinit.js b/test/data/testinit.js index 450f0f19..c4fd7df7 100644 --- a/test/data/testinit.js +++ b/test/data/testinit.js @@ -63,6 +63,7 @@ "unit/jquery/attributes.js", "unit/jquery/css.js", "unit/jquery/data.js", + "unit/jquery/data-jquery-compat.js", "unit/jquery/deferred.js", "unit/jquery/effects.js", "unit/jquery/event.js", diff --git a/test/unit/jquery/data-jquery-compat.js b/test/unit/jquery/data-jquery-compat.js new file mode 100644 index 00000000..29a30554 --- /dev/null +++ b/test/unit/jquery/data-jquery-compat.js @@ -0,0 +1,949 @@ +// This module contains a copy of most of the `data` tests from +// jQuery's `3.x-stable` (with some modifications) to make sure our patches +// don't break compatibility with jQuery. + +/* eslint-disable max-len */ +// Disable `max-len` due to too many violations. + +QUnit.module( "data-jquery-compat", { + beforeEach: function() { + + var template = "" + + "
" + + "

Everything inside the red border is inside a div with id='foo'.

" + + "
" + + "\n" + + "
" + + " " + + " " + + " " + + "
"; + + jQuery( "#qunit-fixture" ).append( template ); + } +} ); + +QUnit.test( "expando", function( assert ) { + assert.expect( 1 ); + + assert.equal( jQuery.expando !== undefined, true, "jQuery is exposing the expando" ); +} ); + +QUnit.test( "jQuery.data & removeData, expected returns", function( assert ) { + assert.expect( 4 ); + var elem = document.body; + + assert.equal( + jQuery.data( elem, "hello", "world" ), "world", + "jQuery.data( elem, key, value ) returns value" + ); + assert.equal( + jQuery.data( elem, "hello" ), "world", + "jQuery.data( elem, key ) returns value" + ); + assert.deepEqual( + jQuery.data( elem, { goodnight: "moon" } ), { goodnight: "moon" }, + "jQuery.data( elem, obj ) returns obj" + ); + assert.equal( + jQuery.removeData( elem, "hello" ), undefined, + "jQuery.removeData( elem, key, value ) returns undefined" + ); + +} ); + +QUnit.test( "jQuery._data & _removeData, expected returns", function( assert ) { + assert.expect( 4 ); + var elem = document.body; + + assert.equal( + jQuery._data( elem, "hello", "world" ), "world", + "jQuery._data( elem, key, value ) returns value" + ); + assert.equal( + jQuery._data( elem, "hello" ), "world", + "jQuery._data( elem, key ) returns value" + ); + assert.deepEqual( + jQuery._data( elem, { goodnight: "moon" } ), { goodnight: "moon" }, + "jQuery._data( elem, obj ) returns obj" + ); + assert.equal( + jQuery._removeData( elem, "hello" ), undefined, + "jQuery._removeData( elem, key, value ) returns undefined" + ); +} ); + +QUnit.test( "jQuery.hasData no side effects", function( assert ) { + assert.expect( 1 ); + var obj = {}; + + jQuery.hasData( obj ); + + assert.equal( Object.getOwnPropertyNames( obj ).length, 0, + "No data expandos where added when calling jQuery.hasData(o)" + ); +} ); + +function dataTests( elem, assert ) { + var dataObj, internalDataObj; + + assert.equal( jQuery.data( elem, "foo" ), undefined, "No data exists initially" ); + assert.strictEqual( jQuery.hasData( elem ), false, "jQuery.hasData agrees no data exists initially" ); + + dataObj = jQuery.data( elem ); + assert.equal( typeof dataObj, "object", "Calling data with no args gives us a data object reference" ); + assert.strictEqual( jQuery.data( elem ), dataObj, "Calling jQuery.data returns the same data object when called multiple times" ); + + assert.strictEqual( jQuery.hasData( elem ), false, "jQuery.hasData agrees no data exists even when an empty data obj exists" ); + + dataObj.foo = "bar"; + if ( !jQuery.data( elem, "foo" ) ) { + debugger; + } + assert.equal( jQuery.data( elem, "foo" ), "bar", "Data is readable by jQuery.data when set directly on a returned data object" ); + + assert.strictEqual( jQuery.hasData( elem ), true, "jQuery.hasData agrees data exists when data exists" ); + + jQuery.data( elem, "foo", "baz" ); + assert.equal( jQuery.data( elem, "foo" ), "baz", "Data can be changed by jQuery.data" ); + assert.equal( dataObj.foo, "baz", "Changes made through jQuery.data propagate to referenced data object" ); + + jQuery.data( elem, "foo", undefined ); + assert.equal( jQuery.data( elem, "foo" ), "baz", "Data is not unset by passing undefined to jQuery.data" ); + + jQuery.data( elem, "foo", null ); + assert.strictEqual( jQuery.data( elem, "foo" ), null, "Setting null using jQuery.data works OK" ); + + jQuery.data( elem, "foo", "foo1" ); + + jQuery.data( elem, { "bar": "baz", "boom": "bloz" } ); + assert.strictEqual( jQuery.data( elem, "foo" ), "foo1", "Passing an object extends the data object instead of replacing it" ); + assert.equal( jQuery.data( elem, "boom" ), "bloz", "Extending the data object works" ); + + jQuery._data( elem, "foo", "foo2", true ); + assert.equal( jQuery._data( elem, "foo" ), "foo2", "Setting internal data works" ); + assert.equal( jQuery.data( elem, "foo" ), "foo1", "Setting internal data does not override user data" ); + + internalDataObj = jQuery._data( elem ); + assert.ok( internalDataObj, "Internal data object exists" ); + assert.notStrictEqual( dataObj, internalDataObj, "Internal data object is not the same as user data object" ); + + assert.strictEqual( elem.boom, undefined, "Data is never stored directly on the object" ); + + jQuery.removeData( elem, "foo" ); + assert.strictEqual( jQuery.data( elem, "foo" ), undefined, "jQuery.removeData removes single properties" ); + + jQuery.removeData( elem ); + assert.strictEqual( jQuery._data( elem ), internalDataObj, "jQuery.removeData does not remove internal data if it exists" ); + + jQuery.data( elem, "foo", "foo1" ); + jQuery._data( elem, "foo", "foo2" ); + + assert.equal( jQuery.data( elem, "foo" ), "foo1", "(sanity check) Ensure data is set in user data object" ); + assert.equal( jQuery._data( elem, "foo" ), "foo2", "(sanity check) Ensure data is set in internal data object" ); + + assert.strictEqual( jQuery._data( elem, jQuery.expando ), undefined, "Removing the last item in internal data destroys the internal data object" ); + + jQuery._data( elem, "foo", "foo2" ); + assert.equal( jQuery._data( elem, "foo" ), "foo2", "(sanity check) Ensure data is set in internal data object" ); + + jQuery.removeData( elem, "foo" ); + assert.equal( jQuery._data( elem, "foo" ), "foo2", "(sanity check) jQuery.removeData for user data does not remove internal data" ); +} + +QUnit.test( "jQuery.data(div)", function( assert ) { + assert.expect( 25 ); + + var div = document.createElement( "div" ); + + dataTests( div, assert ); +} ); + +QUnit.test( "jQuery.data({})", function( assert ) { + assert.expect( 25 ); + + dataTests( {}, assert ); +} ); + +QUnit.test( "jQuery.data(window)", function( assert ) { + assert.expect( 25 ); + + try { + + // Remove bound handlers from window object to stop potential false + // positives caused by fix for trac-5280 in transports/xhr.js. + jQuery( window ).off( "unload" ); + + dataTests( window, assert ); + } finally { + jQuery.removeData( window ); + jQuery._removeData( window ); + } +} ); + +QUnit.test( "jQuery.data(document)", function( assert ) { + assert.expect( 25 ); + + dataTests( document, assert ); +} ); + +QUnit.test( "jQuery.data()", function( assert ) { + assert.expect( 25 ); + + dataTests( document.createElement( "embed" ), assert ); +} ); + +QUnit.test( "jQuery.data(object/flash)", function( assert ) { + assert.expect( 25 ); + + var flash = document.createElement( "object" ); + flash.setAttribute( "classid", "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ); + + dataTests( flash, assert ); +} ); + +// attempting to access the data of an undefined jQuery element should be undefined +QUnit.test( "jQuery().data() === undefined (trac-14101)", function( assert ) { + assert.expect( 2 ); + + assert.strictEqual( jQuery().data(), undefined ); + assert.strictEqual( jQuery().data( "key" ), undefined ); +} ); + +QUnit.test( ".data()", function( assert ) { + assert.expect( 5 ); + + var div, dataObj, nodiv, obj; + + div = jQuery( "#foo" ); + assert.strictEqual( div.data( "foo" ), undefined, "Make sure that missing result is undefined" ); + div.data( "test", "success" ); + + dataObj = div.data(); + + assert.deepEqual( dataObj, { test: "success" }, "data() returns entire data object with expected properties" ); + assert.strictEqual( div.data( "foo" ), undefined, "Make sure that missing result is still undefined" ); + + nodiv = jQuery( "#unfound" ); + assert.equal( nodiv.data(), null, "data() on empty set returns null" ); + + obj = { foo: "bar" }; + jQuery( obj ).data( "foo", "baz" ); + + dataObj = jQuery.extend( true, {}, jQuery( obj ).data() ); + + assert.deepEqual( dataObj, { "foo": "baz" }, "Retrieve data object from a wrapped JS object (trac-7524)" ); +} ); + +function testDataTypes( $obj, assert ) { + jQuery.each( { + "null": null, + "true": true, + "false": false, + "zero": 0, + "one": 1, + "empty string": "", + "empty array": [], + "array": [ 1 ], + "empty object": {}, + "object": { foo: "bar" }, + "date": new Date(), + "regex": /test/, + "function": function() {} + }, function( type, value ) { + assert.strictEqual( $obj.data( "test", value ).data( "test" ), value, "Data set to " + type ); + } ); +} + +QUnit.test( "jQuery(Element).data(String, Object).data(String)", function( assert ) { + assert.expect( 18 ); + var parent = jQuery( "
" ), + div = parent.children(); + + assert.strictEqual( div.data( "test" ), undefined, "No data exists initially" ); + assert.strictEqual( div.data( "test", "success" ).data( "test" ), "success", "Data added" ); + assert.strictEqual( div.data( "test", "overwritten" ).data( "test" ), "overwritten", "Data overwritten" ); + assert.strictEqual( div.data( "test", undefined ).data( "test" ), "overwritten", ".data(key,undefined) does nothing but is chainable (trac-5571)" ); + assert.strictEqual( div.data( "notexist" ), undefined, "No data exists for unset key" ); + testDataTypes( div, assert ); + + parent.remove(); +} ); + +QUnit.test( "jQuery(plain Object).data(String, Object).data(String)", function( assert ) { + assert.expect( 16 ); + + // trac-3748 + var $obj = jQuery( { exists: true } ); + assert.strictEqual( $obj.data( "nothing" ), undefined, "Non-existent data returns undefined" ); + assert.strictEqual( $obj.data( "exists" ), undefined, "Object properties are not returned as data" ); + testDataTypes( $obj, assert ); + + // Clean up + $obj.removeData(); + assert.deepEqual( $obj[ 0 ], { exists: true }, "removeData does not clear the object" ); +} ); + +QUnit.test( ".data(object) does not retain references. trac-13815", function( assert ) { + assert.expect( 2 ); + + var $divs = jQuery( "
" ).appendTo( "#qunit-fixture" ); + + $divs.data( { "type": "foo" } ); + $divs.eq( 0 ).data( "type", "bar" ); + + assert.equal( $divs.eq( 0 ).data( "type" ), "bar", "Correct updated value" ); + assert.equal( $divs.eq( 1 ).data( "type" ), "foo", "Original value retained" ); +} ); + +QUnit.test( "data-* attributes", function( assert ) { + assert.expect( 46 ); + + var prop, i, l, metadata, elem, + obj, obj2, check, num, num2, + parseJSON = JSON.parse, + div = jQuery( "
" ), + child = jQuery( "
" ), + dummy = jQuery( "
" ); + + assert.equal( div.data( "attr" ), undefined, "Check for non-existing data-attr attribute" ); + + div.attr( "data-attr", "exists" ); + assert.equal( div.data( "attr" ), "exists", "Check for existing data-attr attribute" ); + + div.attr( "data-attr", "exists2" ); + assert.equal( div.data( "attr" ), "exists", "Check that updates to data- don't update .data()" ); + + div.data( "attr", "internal" ).attr( "data-attr", "external" ); + assert.equal( div.data( "attr" ), "internal", "Check for .data('attr') precedence (internal > external data-* attribute)" ); + + div.remove(); + + child.appendTo( "#qunit-fixture" ); + assert.equal( child.data( "myobj" ), "old data", "Value accessed from data-* attribute" ); + assert.equal( child.data( "foo-42" ), "boosh", "camelCasing does not affect numbers (gh-1751)" ); + + child.data( "myobj", "replaced" ); + assert.equal( child.data( "myobj" ), "replaced", "Original data overwritten" ); + + child.data( "ignored", "cache" ); + assert.equal( child.data( "ignored" ), "cache", "Cached data used before DOM data-* fallback" ); + + obj = child.data(); + obj2 = dummy.data(); + check = [ "myobj", "ignored", "other", "foo-42" ]; + num = 0; + num2 = 0; + + dummy.remove(); + + for ( i = 0, l = check.length; i < l; i++ ) { + assert.ok( obj[ check[ i ] ], "Make sure data- property exists when calling data-." ); + assert.ok( obj2[ check[ i ] ], "Make sure data- property exists when calling data-." ); + } + + for ( prop in obj ) { + num++; + } + + assert.equal( num, check.length, "Make sure that the right number of properties came through." ); + + /* eslint-disable-next-line no-unused-vars */ + for ( prop in obj2 ) { + num2++; + } + + assert.equal( num2, check.length, "Make sure that the right number of properties came through." ); + + child.attr( "data-other", "newvalue" ); + + assert.equal( child.data( "other" ), "test", "Make sure value was pulled in properly from a .data()." ); + + // attribute parsing + i = 0; + JSON.parse = function() { + i++; + return parseJSON.apply( this, arguments ); + }; + + child + .attr( "data-true", "true" ) + .attr( "data-false", "false" ) + .attr( "data-five", "5" ) + .attr( "data-point", "5.5" ) + .attr( "data-pointe", "5.5E3" ) + .attr( "data-grande", "5.574E9" ) + .attr( "data-hexadecimal", "0x42" ) + .attr( "data-pointbad", "5..5" ) + .attr( "data-pointbad2", "-." ) + .attr( "data-bigassnum", "123456789123456789123456789" ) + .attr( "data-badjson", "{123}" ) + .attr( "data-badjson2", "[abc]" ) + .attr( "data-notjson", " {}" ) + .attr( "data-notjson2", "[] " ) + .attr( "data-empty", "" ) + .attr( "data-space", " " ) + .attr( "data-null", "null" ) + .attr( "data-string", "test" ); + + assert.strictEqual( child.data( "true" ), true, "Primitive true read from attribute" ); + assert.strictEqual( child.data( "false" ), false, "Primitive false read from attribute" ); + assert.strictEqual( child.data( "five" ), 5, "Integer read from attribute" ); + assert.strictEqual( child.data( "point" ), 5.5, "Floating-point number read from attribute" ); + assert.strictEqual( child.data( "pointe" ), "5.5E3", + "Exponential-notation number read from attribute as string" ); + assert.strictEqual( child.data( "grande" ), "5.574E9", + "Big exponential-notation number read from attribute as string" ); + assert.strictEqual( child.data( "hexadecimal" ), "0x42", + "Hexadecimal number read from attribute as string" ); + assert.strictEqual( child.data( "pointbad" ), "5..5", + "Extra-point non-number read from attribute as string" ); + assert.strictEqual( child.data( "pointbad2" ), "-.", + "No-digit non-number read from attribute as string" ); + assert.strictEqual( child.data( "bigassnum" ), "123456789123456789123456789", + "Bad bigass number read from attribute as string" ); + assert.strictEqual( child.data( "badjson" ), "{123}", "Bad JSON object read from attribute as string" ); + assert.strictEqual( child.data( "badjson2" ), "[abc]", "Bad JSON array read from attribute as string" ); + assert.strictEqual( child.data( "notjson" ), " {}", + "JSON object with leading non-JSON read from attribute as string" ); + assert.strictEqual( child.data( "notjson2" ), "[] ", + "JSON array with trailing non-JSON read from attribute as string" ); + assert.strictEqual( child.data( "empty" ), "", "Empty string read from attribute" ); + assert.strictEqual( child.data( "space" ), " ", "Whitespace string read from attribute" ); + assert.strictEqual( child.data( "null" ), null, "Primitive null read from attribute" ); + assert.strictEqual( child.data( "string" ), "test", "Typical string read from attribute" ); + assert.equal( i, 2, "Correct number of JSON parse attempts when reading from attributes" ); + + JSON.parse = parseJSON; + child.remove(); + + // tests from metadata plugin + function testData( index, elem ) { + switch ( index ) { + case 0: + assert.equal( jQuery( elem ).data( "foo" ), "bar", "Check foo property" ); + assert.equal( jQuery( elem ).data( "bar" ), "baz", "Check baz property" ); + break; + case 1: + assert.equal( jQuery( elem ).data( "test" ), "bar", "Check test property" ); + assert.equal( jQuery( elem ).data( "bar" ), "baz", "Check bar property" ); + break; + case 2: + assert.equal( jQuery( elem ).data( "zoooo" ), "bar", "Check zoooo property" ); + assert.deepEqual( jQuery( elem ).data( "bar" ), { "test": "baz" }, "Check bar property" ); + break; + case 3: + assert.equal( jQuery( elem ).data( "number" ), true, "Check number property" ); + assert.deepEqual( jQuery( elem ).data( "stuff" ), [ 2, 8 ], "Check stuff property" ); + break; + default: + assert.ok( false, [ "Assertion failed on index ", index, ", with data" ].join( "" ) ); + } + } + + metadata = "
  1. Some stuff
  2. Some stuff
  3. Some stuff
  4. Some stuff
"; + elem = jQuery( metadata ).appendTo( "#qunit-fixture" ); + + elem.find( "li" ).each( testData ); + elem.remove(); +} ); + +QUnit.test( ".data(Object)", function( assert ) { + assert.expect( 4 ); + + var obj, jqobj, + div = jQuery( "
" ); + + div.data( { "test": "in", "test2": "in2" } ); + assert.equal( div.data( "test" ), "in", "Verify setting an object in data" ); + assert.equal( div.data( "test2" ), "in2", "Verify setting an object in data" ); + + obj = { test: "unset" }; + jqobj = jQuery( obj ); + + jqobj.data( "test", "unset" ); + jqobj.data( { "test": "in", "test2": "in2" } ); + assert.equal( jQuery.data( obj ).test, "in", "Verify setting an object on an object extends the data object" ); + assert.equal( obj.test2, undefined, "Verify setting an object on an object does not extend the object" ); + + // manually clean up detached elements + div.remove(); +} ); + +QUnit.test( "jQuery.removeData", function( assert ) { + assert.expect( 10 ); + + var obj, + div = jQuery( "#foo" )[ 0 ]; + jQuery.data( div, "test", "testing" ); + jQuery.removeData( div, "test" ); + assert.equal( jQuery.data( div, "test" ), undefined, "Check removal of data" ); + + jQuery.data( div, "test2", "testing" ); + jQuery.removeData( div ); + assert.ok( !jQuery.data( div, "test2" ), "Make sure that the data property no longer exists." ); + assert.ok( !div[ jQuery.expando ], "Make sure the expando no longer exists, as well." ); + + jQuery.data( div, { + test3: "testing", + test4: "testing" + } ); + jQuery.removeData( div, "test3 test4" ); + assert.ok( !jQuery.data( div, "test3" ) || jQuery.data( div, "test4" ), "Multiple delete with spaces." ); + + jQuery.data( div, { + test3: "testing", + test4: "testing" + } ); + jQuery.removeData( div, [ "test3", "test4" ] ); + assert.ok( !jQuery.data( div, "test3" ) || jQuery.data( div, "test4" ), "Multiple delete by array." ); + + jQuery.data( div, { + "test3 test4": "testing", + "test3": "testing" + } ); + jQuery.removeData( div, "test3 test4" ); + assert.ok( !jQuery.data( div, "test3 test4" ), "Multiple delete with spaces deleted key with exact name" ); + assert.ok( jQuery.data( div, "test3" ), "Left the partial matched key alone" ); + + obj = {}; + jQuery.data( obj, "test", "testing" ); + assert.equal( jQuery( obj ).data( "test" ), "testing", "verify data on plain object" ); + jQuery.removeData( obj, "test" ); + assert.equal( jQuery.data( obj, "test" ), undefined, "Check removal of data on plain object" ); + + jQuery.data( window, "BAD", true ); + jQuery.removeData( window, "BAD" ); + assert.ok( !jQuery.data( window, "BAD" ), "Make sure that the value was not still set." ); +} ); + +QUnit.test( ".removeData()", function( assert ) { + assert.expect( 6 ); + var div = jQuery( "#foo" ); + div.data( "test", "testing" ); + div.removeData( "test" ); + assert.equal( div.data( "test" ), undefined, "Check removal of data" ); + + div.data( "test", "testing" ); + div.data( "test.foo", "testing2" ); + div.removeData( "test.bar" ); + assert.equal( div.data( "test.foo" ), "testing2", "Make sure data is intact" ); + assert.equal( div.data( "test" ), "testing", "Make sure data is intact" ); + + div.removeData( "test" ); + assert.equal( div.data( "test.foo" ), "testing2", "Make sure data is intact" ); + assert.equal( div.data( "test" ), undefined, "Make sure data is intact" ); + + div.removeData( "test.foo" ); + assert.equal( div.data( "test.foo" ), undefined, "Make sure data is intact" ); +} ); + +QUnit.test( "JSON serialization (trac-8108)", function( assert ) { + assert.expect( 1 ); + + var obj = { "foo": "bar" }; + jQuery.data( obj, "hidden", true ); + + assert.equal( JSON.stringify( obj ), "{\"foo\":\"bar\"}", "Expando is hidden from JSON.stringify" ); +} ); + +QUnit.test( ".data should follow html5 specification regarding camel casing", function( assert ) { + assert.expect( 12 ); + + var div = jQuery( "
" ) + .prependTo( "body" ); + + assert.equal( div.data().wTF, "ftw", "Verify single letter data-* key" ); + assert.equal( div.data().bigALittleA, "bouncing-b", "Verify single letter mixed data-* key" ); + + assert.equal( div.data().foo, "a", "Verify single word data-* key" ); + assert.equal( div.data().fooBar, "b", "Verify multiple word data-* key" ); + assert.equal( div.data().fooBarBaz, "c", "Verify multiple word data-* key" ); + + assert.equal( div.data( "foo" ), "a", "Verify single word data-* key" ); + assert.equal( div.data( "fooBar" ), "b", "Verify multiple word data-* key" ); + assert.equal( div.data( "fooBarBaz" ), "c", "Verify multiple word data-* key" ); + + div.data( "foo-bar", "d" ); + + assert.equal( div.data( "fooBar" ), "d", "Verify updated data-* key" ); + assert.equal( div.data( "foo-bar" ), "d", "Verify updated data-* key" ); + + assert.equal( div.data( "fooBar" ), "d", "Verify updated data-* key (fooBar)" ); + assert.equal( div.data( "foo-bar" ), "d", "Verify updated data-* key (foo-bar)" ); + + div.remove(); +} ); + +QUnit.test( ".data should not miss preset data-* w/ hyphenated property names", function( assert ) { + + assert.expect( 2 ); + + var div = jQuery( "
", { id: "hyphened" } ).appendTo( "#qunit-fixture" ), + test = { + "camelBar": "camelBar", + "hyphen-foo": "hyphen-foo" + }; + + div.data( test ); + + jQuery.each( test, function( i, k ) { + assert.equal( div.data( k ), k, "data with property '" + k + "' was correctly found" ); + } ); +} ); + +QUnit.test( "jQuery.data should not miss data-* w/ hyphenated property names trac-14047", function( assert ) { + + assert.expect( 1 ); + + var div = jQuery( "
" ); + + div.data( "foo-bar", "baz" ); + + assert.equal( jQuery.data( div[ 0 ], "foo-bar" ), "baz", "data with property 'foo-bar' was correctly found" ); +} ); + +QUnit.test( ".data should not miss attr() set data-* with hyphenated property names", function( assert ) { + assert.expect( 2 ); + + var a, b; + + a = jQuery( "
" ).appendTo( "#qunit-fixture" ); + + a.attr( "data-long-param", "test" ); + a.data( "long-param", { a: 2 } ); + + assert.deepEqual( a.data( "long-param" ), { a: 2 }, "data with property long-param was found, 1" ); + + b = jQuery( "
" ).appendTo( "#qunit-fixture" ); + + b.attr( "data-long-param", "test" ); + b.data( "long-param" ); + b.data( "long-param", { a: 2 } ); + + assert.deepEqual( b.data( "long-param" ), { a: 2 }, "data with property long-param was found, 2" ); +} ); + +QUnit.test( ".data always sets data with the camelCased key (gh-2257)", function( assert ) { + assert.expect( 18 ); + + var div = jQuery( "
" ).appendTo( "#qunit-fixture" ), + datas = { + "non-empty": { + key: "nonEmpty", + value: "a string" + }, + "empty-string": { + key: "emptyString", + value: "" + }, + "one-value": { + key: "oneValue", + value: 1 + }, + "zero-value": { + key: "zeroValue", + value: 0 + }, + "an-array": { + key: "anArray", + value: [] + }, + "an-object": { + key: "anObject", + value: {} + }, + "bool-true": { + key: "boolTrue", + value: true + }, + "bool-false": { + key: "boolFalse", + value: false + }, + + // JSHint enforces double quotes, + // but JSON strings need double quotes to parse + // so we need escaped double quotes here + "some-json": { + key: "someJson", + value: "{ \"foo\": \"bar\" }" + } + }; + + jQuery.each( datas, function( key, val ) { + div.data( key, val.value ); + var allData = div.data(); + assert.equal( allData[ key ], undefined, ".data does not store with hyphenated keys" ); + assert.equal( allData[ val.key ], val.value, ".data stores the camelCased key" ); + } ); +} ); + +QUnit.test( ".data should not strip more than one hyphen when camelCasing (gh-2070)", function( assert ) { + assert.expect( 3 ); + var div = jQuery( "
" ).appendTo( "#qunit-fixture" ), + allData = div.data(); + + assert.equal( allData.nestedSingle, "single", "Key is correctly camelCased" ); + assert.equal( allData[ "nested-Double" ], "double", "Key with double hyphens is correctly camelCased" ); + assert.equal( allData[ "nested--Triple" ], "triple", "Key with triple hyphens is correctly camelCased" ); +} ); + +QUnit.test( ".data supports interoperable hyphenated/camelCase get/set of properties with arbitrary non-null|NaN|undefined values", function( assert ) { + + var div = jQuery( "
", { id: "hyphened" } ).appendTo( "#qunit-fixture" ), + datas = { + "non-empty": { + key: "nonEmpty", + value: "a string" + }, + "empty-string": { + key: "emptyString", + value: "" + }, + "one-value": { + key: "oneValue", + value: 1 + }, + "zero-value": { + key: "zeroValue", + value: 0 + }, + "an-array": { + key: "anArray", + value: [] + }, + "an-object": { + key: "anObject", + value: {} + }, + "bool-true": { + key: "boolTrue", + value: true + }, + "bool-false": { + key: "boolFalse", + value: false + }, + + // JSHint enforces double quotes, + // but JSON strings need double quotes to parse + // so we need escaped double quotes here + "some-json": { + key: "someJson", + value: "{ \"foo\": \"bar\" }" + }, + + "num-1-middle": { + key: "num-1Middle", + value: true + }, + "num-end-2": { + key: "numEnd-2", + value: true + }, + "2-num-start": { + key: "2NumStart", + value: true + } + }; + + assert.expect( 24 ); + + jQuery.each( datas, function( key, val ) { + div.data( key, val.value ); + + assert.deepEqual( div.data( key ), val.value, "get: " + key ); + assert.deepEqual( div.data( val.key ), val.value, "get: " + val.key ); + } ); +} ); + +QUnit.test( ".data supports interoperable removal of hyphenated/camelCase properties", function( assert ) { + var div = jQuery( "
", { id: "hyphened" } ).appendTo( "#qunit-fixture" ), + rdashAlpha = /-([a-z])/g, + datas = { + "non-empty": "a string", + "empty-string": "", + "one-value": 1, + "zero-value": 0, + "an-array": [], + "an-object": {}, + "bool-true": true, + "bool-false": false, + + // JSHint enforces double quotes, + // but JSON strings need double quotes to parse + // so we need escaped double quotes here + "some-json": "{ \"foo\": \"bar\" }" + }; + + assert.expect( 27 ); + + function fcamelCase( all, letter ) { + return letter.toUpperCase(); + } + + jQuery.each( datas, function( key, val ) { + div.data( key, val ); + + assert.deepEqual( div.data( key ), val, "get: " + key ); + assert.deepEqual( + div.data( key.replace( rdashAlpha, fcamelCase ) ), + val, + "get: " + key.replace( rdashAlpha, fcamelCase ) + ); + + div.removeData( key ); + + assert.equal( div.data( key ), undefined, "get: " + key ); + + } ); +} ); + +QUnit.test( ".data supports interoperable removal of properties SET TWICE trac-13850", function( assert ) { + var div = jQuery( "
" ).appendTo( "#qunit-fixture" ), + datas = { + "non-empty": "a string", + "empty-string": "", + "one-value": 1, + "zero-value": 0, + "an-array": [], + "an-object": {}, + "bool-true": true, + "bool-false": false, + + // JSHint enforces double quotes, + // but JSON strings need double quotes to parse + // so we need escaped double quotes here + "some-json": "{ \"foo\": \"bar\" }" + }; + + assert.expect( 9 ); + + jQuery.each( datas, function( key, val ) { + div.data( key, val ); + div.data( key, val ); + + div.removeData( key ); + + assert.equal( div.data( key ), undefined, "removal: " + key ); + } ); +} ); + +QUnit.test( ".removeData supports removal of hyphenated properties via array (trac-12786, gh-2257)", function( assert ) { + + // Tests checking for the shape of the data object prior to `.removeData()` + // calls were not removed since we restore some of the 1.x/2.x behavior. + assert.expect( 2 ); + + var div, plain; + + div = jQuery( "
" ).appendTo( "#qunit-fixture" ); + plain = jQuery( {} ); + + // Mixed assignment + div.data( { "a-a": 1 } ).data( "b-b", 1 ); + plain.data( { "a-a": 1 } ).data( "b-b", 1 ); + + div.removeData( [ "a-a", "b-b" ] ); + plain.removeData( [ "a-a", "b-b" ] ); + + assert.deepEqual( div.data(), {}, "Data is empty. (div)" ); + assert.deepEqual( plain.data(), {}, "Data is empty. (plain)" ); +} ); + +QUnit.test( ".data only checks element attributes once. trac-8909", function( assert ) { + assert.expect( 2 ); + var testing = { + "test": "testing", + "test2": "testing" + }, + element = jQuery( "
" ), + node = element[ 0 ]; + + // set an attribute using attr to ensure it + node.setAttribute( "data-test2", "testing" ); + assert.deepEqual( element.data(), testing, "Sanity Check" ); + + node.setAttribute( "data-test3", "testing" ); + assert.deepEqual( element.data(), testing, "The data didn't change even though the data-* attrs did" ); + + // clean up data cache + element.remove(); +} ); + +QUnit.test( "data-* with JSON value can have newlines", function( assert ) { + assert.expect( 1 ); + + var x = jQuery( "
" ); + assert.equal( x.data( "some" ).foo, "bar", "got a JSON data- attribute with spaces" ); + x.remove(); +} ); + +QUnit.test( ".data doesn't throw when calling selection is empty. trac-13551", function( assert ) { + assert.expect( 1 ); + + try { + jQuery( null ).data( "prop" ); + assert.ok( true, "jQuery(null).data('prop') does not throw" ); + } catch ( e ) { + assert.ok( false, e.message ); + } +} ); + +QUnit.test( "acceptData", function( assert ) { + assert.expect( 10 ); + + var flash, pdf, form; + + assert.equal( jQuery( document ).data( "test", 42 ).data( "test" ), 42, "document" ); + assert.equal( jQuery( document.documentElement ).data( "test", 42 ).data( "test" ), 42, "documentElement" ); + assert.equal( jQuery( {} ).data( "test", 42 ).data( "test" ), 42, "object" ); + assert.equal( jQuery( document.createElement( "embed" ) ).data( "test", 42 ).data( "test" ), 42, "embed" ); + + flash = document.createElement( "object" ); + flash.setAttribute( "classid", "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ); + assert.equal( jQuery( flash ).data( "test", 42 ).data( "test" ), 42, "flash" ); + + pdf = document.createElement( "object" ); + pdf.setAttribute( "classid", "clsid:CA8A9780-280D-11CF-A24D-444553540000" ); + assert.equal( jQuery( pdf ).data( "test", 42 ).data( "test" ), 42, "pdf" ); + + assert.strictEqual( jQuery( document.createComment( "" ) ).data( "test", 42 ).data( "test" ), undefined, "comment" ); + assert.strictEqual( jQuery( document.createTextNode( "" ) ).data( "test", 42 ).data( "test" ), undefined, "text" ); + assert.strictEqual( jQuery( document.createDocumentFragment() ).data( "test", 42 ).data( "test" ), undefined, "documentFragment" ); + + form = jQuery( "#form" ).append( "" )[ 0 ]; + assert.equal( jQuery( form ) .data( "test", 42 ).data( "test" ), 42, "form with aliased DOM properties" ); +} ); + +QUnit.test( "Check proper data removal of non-element descendants nodes (trac-8335)", function( assert ) { + assert.expect( 1 ); + + var div = jQuery( "
text
" ), + text = div.contents(); + + text.data( "test", "test" ); // This should be a noop. + div.remove(); + + assert.ok( !text.data( "test" ), "Be sure data is not stored in non-element" ); +} ); + +QUnit.test( ".data() returns a regular object (jQuery <4 only, gh-4665)", function( assert ) { + assert.expect( 4 ); + + function verifyRegularObject( assert, object ) { + assert.strictEqual( object.hasOwnProperty, Object.prototype.hasOwnProperty, + "Data object has the hasOwnProperty method" ); + assert.strictEqual( object + "", "[object Object]", + "Data object can be stringified" ); + } + + var elem = jQuery( "
" ); + + verifyRegularObject( assert, elem.data() ); + + elem.data( "foo", "bar" ); + verifyRegularObject( assert, elem.data() ); +} ); diff --git a/test/unit/jquery/data.js b/test/unit/jquery/data.js index afe749bf..e487f1e6 100644 --- a/test/unit/jquery/data.js +++ b/test/unit/jquery/data.js @@ -1,104 +1,207 @@ QUnit.module( "data" ); -QUnit.test( "jQuery.data() camelCased names", function( assert ) { - - var sames = [ - "datum", - "ropeAdope", - "Олег\u0007Michał", - "already-Big", - "number-2", - "unidash-" - ], - diffs = [ - "dat-data", - "hangy-dasher-", - "-dashy-hanger" - ]; - - assert.expect( 16 ); - - var curData, - div = document.createElement( "div" ); - - // = .hasData + noWarning - expectNoWarning( assert, "No existing data object", function() { - sames.concat( diffs ).forEach( function( name ) { - jQuery.data( div, name ); - } ); - assert.equal( jQuery.hasData( div ), false, "data probes did not fill a data object" ); +function camelCase( string ) { + return string.replace( /-([a-z])/g, function( _all, letter ) { + return letter.toUpperCase(); } ); +} + +[ + { + apiName: "jQuery.data()", + dataFn: function() { + return jQuery.data.apply( jQuery, arguments ); + } + }, + { + apiName: "jQuery.fn.data()", + dataFn: function( elem ) { + var args = Array.prototype.slice.call( arguments, 1 ); + return jQuery.fn.data.apply( jQuery( elem ), args ); + } + } +].forEach( function( params ) { + var apiName = params.apiName; + var dataFn = params.dataFn; + + QUnit.test( apiName + " camelCased names", function( assert ) { + + var sames = [ + "datum", + "ropeAdope", + "Олег\u0007Michał", + "already-Big", + "number-2", + "unidash-" + ], + diffs = [ + "dat-data", + "hangy-dasher-", + "-dashy-hanger" + ]; + + assert.expect( 16 ); + + var curData, + div = document.createElement( "div" ); + + // = .hasData + noWarning + expectNoWarning( assert, "No existing data object", function() { + sames.concat( diffs ).forEach( function( name ) { + dataFn( div, name ); + } ); + assert.strictEqual( jQuery.hasData( div ), false, + "data probes did not fill a data object" ); + } ); - // = sames.length + diffs.length + noWarning - expectNoWarning( assert, "Data set/get without warning via API", function() { - sames.concat( diffs ).forEach( function( name, index ) { - jQuery.data( div, name, index ); - assert.equal( jQuery.data( div, name ), index, name + "=" + index ); + // = sames.length + diffs.length + noWarning + expectNoWarning( assert, "Data set/get without warning via API", function() { + sames.concat( diffs ).forEach( function( name, index ) { + dataFn( div, name, index ); + assert.strictEqual( dataFn( div, name ), index, name + "=" + index ); + } ); } ); - } ); - // Camelized values set for all names above, get the data object - curData = jQuery.data( div ); + // Camelized values set for all names above, get the data object + curData = dataFn( div ); - // = diffs.length + warning - expectWarning( assert, "Dashed name conflicts", diffs.length, function() { - diffs.forEach( function( name, index ) { - curData[ name ] = index; - assert.equal( jQuery.data( div, name ), curData[ name ], - name + " respects data object" ); + // = diffs.length + warning + expectWarning( assert, "Dashed name conflicts", diffs.length, function() { + diffs.forEach( function( name, index ) { + curData[ name ] = index; + assert.strictEqual( dataFn( div, name ), curData[ name ], + name + " respects data object" ); + } ); } ); - } ); -} ); + } ); -QUnit.test( "jQuery.data() camelCased names (mass setter)", function( assert ) { - var sames = [ - "datum", - "ropeAdope", - "Олег\u0007Michał", - "already-Big", - "number-2", - "unidash-" - ], - diffs = [ - "dat-data", - "hangy-dasher-", - "-dashy-hanger" - ]; - - assert.expect( 11 ); - - var div = document.createElement( "div" ); - - // = sames.length + noWarning - expectNoWarning( assert, "Data set as an object and get without warning via API", function() { - var testData = {}; - - sames.forEach( function( name, index ) { - testData[ name ] = index; + QUnit.test( apiName + " camelCased names (mass setter)", function( assert ) { + var sames = [ + "datum", + "ropeAdope", + "Олег\u0007Michał", + "already-Big", + "number-2", + "unidash-" + ], + diffs = [ + "dat-data", + "hangy-dasher-", + "-dashy-hanger" + ]; + + assert.expect( 18 ); + + var div = document.createElement( "div" ); + + // = sames.length + noWarning + expectNoWarning( assert, "Data set as an object and get without warning via API", + function() { + var testData = {}; + + sames.forEach( function( name, index ) { + testData[ name ] = index; + } ); + + dataFn( div, testData ); + + sames.forEach( function( name, index ) { + assert.strictEqual( dataFn( div, name ), index, name + "=" + index ); + } ); } ); - jQuery.data( div, testData ); + // = diffs.length + warning + expectWarning( assert, "Data set as an object and get without warning via API", + function() { + var testData = {}; + + diffs.forEach( function( name, index ) { + testData[ name ] = index; + } ); - sames.forEach( function( name, index ) { - assert.equal( jQuery.data( div, name ), index, name + "=" + index ); + dataFn( div, testData ); + + diffs.forEach( function( name, index ) { + assert.strictEqual( dataFn( div, name ), index, name + "=" + index ); + } ); + } ); + + // Make sure for non-camel keys both the provided & camelCased versions + // have data saved under them. + expectNoWarning( assert, "Data object contents", function() { + var dataObj = dataFn( div ); + diffs.forEach( function( name, index ) { + assert.strictEqual( dataObj[ name ], index, name + "=" + index ); + assert.strictEqual( dataObj[ camelCase( name ) ], index, + camelCase( name ) + "=" + index ); + } ); } ); + } ); - // = diffs.length + warning - expectWarning( assert, "Data set as an object and get without warning via API", function() { - var testData = {}; +} ); - diffs.forEach( function( name, index ) { - testData[ name ] = index; - } ); +QUnit.test( ".removeData()", function( assert ) { + assert.expect( 5 ); - jQuery.data( div, testData ); + var div1 = jQuery( "
" ).appendTo( "#qunit-fixture" ), + div2 = jQuery( "
" ).appendTo( "#qunit-fixture" ); - diffs.forEach( function( name, index ) { - assert.equal( jQuery.data( div, name ), index, name + "=" + index ); - } ); + // Mixed assignment + div1.add( div2 ) + .data( { "a-a-a": 1, "b-bB": 2, "cCC": 3 } ) + .data( "d-d-d", 4 ) + .data( "e-eE", 5 ) + .data( "fFF", 6 ); + + expectNoWarning( assert, "camelCase args", function() { + div1 + .removeData( "aAA cCC eEE" ) + .removeData( [ "bBB", "dDD", "fFF" ] ); + } ); + + expectWarning( assert, "Not camelCase args originally present", 2, function() { + + // We expect two warnings as only the object-set keys are set + // in their original form. + div2 + .removeData( "a-a-a e-eE" ) + .removeData( [ "d-d-d", "b-bB" ] ); } ); + expectNoWarning( assert, "Not camelCase args originally missing", function() { + div2 + .removeData( "c-cC" ) + .removeData( [ "f-f-f" ] ); + } ); + + // Divergence from jQuery 3.x: partially camelCased keys set in the object + // setter need to be passed in the same form when removing. + div1.removeData( "b-bB" ); + + assert.deepEqual( div1.data(), {}, "Data is empty. (div1)" ); + assert.deepEqual( div2.data(), {}, "Data is empty. (div2)" ); } ); +QUnit.test( "properties from Object.prototype", function( assert ) { + assert.expect( 6 ); + + var div = jQuery( "
" ).appendTo( "#qunit-fixture" ); + + div.data( "foo", "bar" ); + + expectNoWarning( assert, "Regular properties", function() { + assert.strictEqual( div.data( "foo" ), "bar", "data access" ); + assert.strictEqual( jQuery.data( div[ 0 ], "foo" ), "bar", "data access (static method)" ); + } ); + + ( + Object.setPrototypeOf ? expectWarning : expectNoWarning + )( assert, "Properties from Object.prototype", 2, function() { + assert.ok( div.data().hasOwnProperty( "foo" ), + "hasOwnProperty works" ); + assert.ok( jQuery.data( div[ 0 ] ).hasOwnProperty( "foo" ), + "hasOwnProperty works (static method)" ); + } ); +} ); diff --git a/warnings.md b/warnings.md index 465be03c..e6979b68 100644 --- a/warnings.md +++ b/warnings.md @@ -97,6 +97,15 @@ This is _not_ a warning, but a console log message the plugin shows when it firs **Solution:** Either 1) Always use the `.data()` API to set or get data items, 2) Always use camelCase names when also setting properties directly on jQuery's data object, or 3) Always set properties directly on the data object without using the API call to set or get data by name. Never mix direct access to the data object and API calls with kebab case names. +### \[data-null-proto\] Accessing properties from jQuery.data() inherited from Object.prototype is deprecated +### \[data-null-proto\] Setting properties from jQuery.data() inherited from Object.prototype is deprecated +### \[data-null-proto\] Accessing properties from jQuery.fn.data() inherited from Object.prototype is deprecated +### \[data-null-proto\] Setting properties from jQuery.fn.data() inherited from Object.prototype is deprecated + +**Cause:** Accessing or setting properties on data objects inherited from `Object.prototype` is deprecated. This includes properties like `__proto__` or `hasOwnProperty`. + +**Solution:** Don't use properties inherited from `Object.prototype` on data objects. Instead of `jQuery.data( node ).hasOwnProperty( "foo" )` use `Object.hasOwn( jQuery.data( node ), "foo" )` or, if you need to support older browsers like IE 11, use `Object.prototype.hasOwnProperty.call( jQuery.data( node ), "foo" )`. + ### \[removeAttr-bool\] JQMIGRATE: jQuery.fn.removeAttr no longer sets boolean properties **Cause**: Prior to jQuery 3.0, using `.removeAttr()` on a boolean attribute such as `checked`, `selected`, or `readonly` would also set the corresponding named *property* to `false`. This behavior was required for ancient versions of Internet Explorer but is not correct for modern browsers because the attribute represents the initial value and the property represents the current (dynamic) value.