Reputation: 67
I can't fully understand how Object.defineProperty
works on dom elements.
On normal javascript objects it works like a charm
var obj={name: 'john'};
Object.defineProperty(obj, 'name', {
get: function(){
console.log('get value')
},
set:function(newValue){
console.log('set value '+newValue);
},
configurable: true
});
the line
obj.name='Tom';
will print to console 'set value Tom' and change obj.name to Tom.
When I try it on a dom element (e.g. on the property checked of a checkbox), it will print the new value in the console, but will not change the value of the property:
var box = document.getElementById('checkBox1');
Object.defineProperty(box, 'checked', {
set: function (newValue) {
console.log('set value '+newValue)
},
configurable: true
});
clicking on an unchecked checkbox will output 'set value checked'. But nothing changes on screen, neither in the object box. The setter of the checkbox just stops working. Like if I have 'disabled' it.
Where am I wrong?
Upvotes: 3
Views: 1402
Reputation: 1075159
That's because you've never set the value in your setter. When you create a setter, you're taking over the job of handling setting the value on the object (on the element, in your case). (And if you try to set it in your setter, e.g. box.checked = newValue
, you'll just go into a loop that will only end because of a stack overflow.)
Looking at your code, you're trying to get notification when the checked
property of a DOM element is changed. You can't do that with defineProperty
. Host objects (like DOM elements) don't have to support defineProperty
at all, and even if they do, they don't have to call the setter when the underlying state of the control changes internally.
Upvotes: 3