Object.defineProperty: setters for dom elements properties

放肆的年华 提交于 2020-07-21 07:13:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/41545467/object-defineproperty-setters-for-dom-elements-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!