Avoid side-effects when calling jQuery.hasData

Signed-off-by: Rick Waldron <waldron.rick@gmail.com>
This commit is contained in:
Rick Waldron 2013-04-01 12:48:30 -04:00
parent 1f530e2867
commit 332a490573
2 changed files with 19 additions and 2 deletions

View File

@ -21,11 +21,17 @@ function Data() {
Data.uid = 1; Data.uid = 1;
Data.prototype = { Data.prototype = {
key: function( owner ) { key: function( owner, options ) {
var descriptor = {}, var descriptor = {},
// Check if the owner object already has a cache key // Check if the owner object already has a cache key
unlock = owner[ this.expando ]; unlock = owner[ this.expando ];
// `readonly` calls from hasData, on owners with no key
// should not create new/empty cache records
if ( !unlock && (options && options.readonly) ) {
return null;
}
// If not, create one // If not, create one
if ( !unlock ) { if ( !unlock ) {
unlock = Data.uid++; unlock = Data.uid++;
@ -158,7 +164,7 @@ Data.prototype = {
}, },
hasData: function( owner ) { hasData: function( owner ) {
return !jQuery.isEmptyObject( return !jQuery.isEmptyObject(
this.cache[ this.key( owner ) ] this.cache[ this.key( owner, { readonly: true }) ] || {}
); );
}, },
discard: function( owner ) { discard: function( owner ) {

View File

@ -51,6 +51,17 @@ test( "jQuery._data & _removeData, expected returns", function() {
); );
}); });
test( "jQuery.hasData no side effects", function() {
expect(1);
var obj = {};
jQuery.hasData( obj );
equal( Object.getOwnPropertyNames( obj ).length, 0,
"No data expandos where added when calling jQuery.hasData(o)"
);
});
function dataTests (elem) { function dataTests (elem) {
var oldCacheLength, dataObj, internalDataObj, expected, actual; var oldCacheLength, dataObj, internalDataObj, expected, actual;