希望你们都做得很好!我有个小问题,也许你们很多人已经想过.是否有任何解决方案来侦听本机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”、“占位符”等。
总之,我只想观察一些属性而不更改它们的任何默认行为.
有什么想法吗?
谢谢,伙计们!
干杯!
发布于 2018-04-05 19:18:06
您需要首先获得本地属性描述符。你可以从元素的原型中得到一个。
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');https://stackoverflow.com/questions/43349975
复制相似问题