Skip to content

Commit 332a490

Browse files
committedApr 1, 2013
Avoid side-effects when calling jQuery.hasData
Signed-off-by: Rick Waldron <waldron.rick@gmail.com>
1 parent 1f530e2 commit 332a490

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed
 

‎src/data.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,17 @@ function Data() {
2121
Data.uid = 1;
2222

2323
Data.prototype = {
24-
key: function( owner ) {
24+
key: function( owner, options ) {
2525
var descriptor = {},
2626
// Check if the owner object already has a cache key
2727
unlock = owner[ this.expando ];
2828

29+
// `readonly` calls from hasData, on owners with no key
30+
// should not create new/empty cache records
31+
if ( !unlock && (options && options.readonly) ) {
32+
return null;
33+
}
34+
2935
// If not, create one
3036
if ( !unlock ) {
3137
unlock = Data.uid++;
@@ -158,7 +164,7 @@ Data.prototype = {
158164
},
159165
hasData: function( owner ) {
160166
return !jQuery.isEmptyObject(
161-
this.cache[ this.key( owner ) ]
167+
this.cache[ this.key( owner, { readonly: true }) ] || {}
162168
);
163169
},
164170
discard: function( owner ) {

‎test/unit/data.js

+11
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,17 @@ test( "jQuery._data & _removeData, expected returns", function() {
5151
);
5252
});
5353

54+
test( "jQuery.hasData no side effects", function() {
55+
expect(1);
56+
var obj = {};
57+
58+
jQuery.hasData( obj );
59+
60+
equal( Object.getOwnPropertyNames( obj ).length, 0,
61+
"No data expandos where added when calling jQuery.hasData(o)"
62+
);
63+
});
64+
5465
function dataTests (elem) {
5566
var oldCacheLength, dataObj, internalDataObj, expected, actual;
5667

0 commit comments

Comments
 (0)