本机 HTMLElement 属性观察器

native HTMLElement properties observer

希望你们一切都好! 我有一个小问题,也许你们中的很多人已经想过...... 是否有任何解决方案来侦听本机 HTMLElement 属性(而不是属性)更新? 我解释一下:

<input type="text" value="hello" />

我希望在代码库中执行此操作时收到通知:

myInput.value = 'world';

我可以知道属性本身已经用 MutationObserver 或 attributeChangedCallback 函数更新了,但是当代码库直接通过 属性 赋值时却不知道...

我试过这样做:

Object.defineProperty(myInput, 'value', {
   set : (newValue) => {
      console.log('value property updated');
      // I can't do something like this.value = newValue
      // cause it will trigger an infinite loop...
   }
});

问题是现在 myInput.value = 'world'; 的默认行为不再起作用,字段内的值实际上没有改变...

我想将此概念应用到其他属性以及 "min"、"max"、"placeholder" 等...

总而言之,我只想观察一些属性而不改变它们的任何默认行为...

有什么想法吗?

提前谢谢大家!

干杯!

您需要先获取原生 property descriptor。你可以从元素的原型中得到一个。

const nativeValueDesc = Object.getOwnPropertyDescriptor(input.constructor.prototype, 'value');

然后您可以在 setter 和 getter 中使用它来反映本机行为

Object.defineProperty(input,'value',{
  set(val){
    console.log('value property updated', val);
    // Continue with native behavior
    return nativeValueDesc.set.call(this, val);
  }
  /* ... */
});

http://jsbin.com/juqili/6/edit?html,js,console,output

上的实例

为了能够观察已经观察到的元素,或者只是一个已经提供了自己的描述符的元素,你可以这样做

const nativeValueDesc = Object.getOwnPropertyDescriptor(input, 'value') || Object.getOwnPropertyDescriptor(input.constructor.prototype, 'value');