Reputation: 302
I wrote a little Test to describe my Problem:
<div id="test1"></div>
<div id="test2"></div>
<script>
(function ($) {
$.widget("mseh.testIt", {
options : {
foo : false,
bar : false
},
_settedOptions : {
foo : false,
bar : false
},
readOptions : function() {
return this._settedOptions;
},
_init : function() {
this._initializeTest();
},
_initializeTest : function() {
var self = this;
$.each(self.options, function(key, value) {
self._settedOptions[key] = value;
});
}
});
})(jQuery);
$('#test1').testIt({ foo : true, bar : false});
$('#test2').testIt({ foo : true, bar : true});
console.log($('#test1').testIt('readOptions'));
console.log($('#test2').testIt('readOptions'));
</script>
In this example both logs give me a true for 'foo' (as expected) and a true for 'bar' (NOT as expected).
Is this a bug or am i doing something wrong?
Tested with jQuery 1.7.2 and 1.9.1. Tested with jQueryUI 1.9.2 and 1.10.0.
Thanks
Upvotes: 0
Views: 118
Reputation: 196
Because _settedOptions shared in every instance of testIt.
if you check _settedOptions's object equality between test1 and test2 as below, they refers same object.
console.log( $('#test1').testIt('readOptions') === $('#test2').testIt('readOptions') );
if you want to treat it as instance-variable, write below.
(function ($) {
$.widget("mseh.testIt", {
options : {
foo : false,
bar : false
},
// This field will be shared in every instance.
// _settedOptions : {
// foo : false,
// bar : false
// },
readOptions : function() {
return this._settedOptions;
},
_init : function() {
// like this!!!!!
this._settedOptions = {
foo : false,
bar : false
};
this._initializeTest();
},
_initializeTest : function() {
var self = this;
$.each(self.options, function(key, value) {
self._settedOptions[key] = value;
});
}
});
})(jQuery);
Upvotes: 2