Object.defineProperty:DOM元素属性的设置器 [英] Object.defineProperty: setters for dom elements properties

查看:411
本文介绍了Object.defineProperty:DOM元素属性的设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不完全了解Object.defineProperty如何在dom元素上工作. 在普通的javascript对象上,它的工作原理就像一个魅力

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
}); 

线

obj.name='Tom';

将打印到控制台设置值Tom",并将obj.name更改为Tom.

will print to console 'set value Tom' and change obj.name to Tom.

当我在dom元素上尝试时(例如,选中复选框的属性),它将在控制台中打印新值,但不会更改该属性的值:

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.

我在哪里错了?

推荐答案

这是因为您从未在设置器中设置过该值.创建setter时,您要接管设置对象(在您的情况下为元素)上的值的工作. (而且,如果您尝试在设置器中进行设置,例如box.checked = newValue,您将进入一个仅由于堆栈溢出而结束的循环.)

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.)

查看您的代码,您试图在DOM元素的checked属性更改时获得通知.用defineProperty无法做到这一点.宿主对象(例如DOM元素)根本不需要支持defineProperty,即使它们支持,当控件的基础状态在内部发生变化时,它们也不必调用setter.

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.

这篇关于Object.defineProperty:DOM元素属性的设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆