我有一个继承自 HTMLInputElement
的自定义输入框:
class TB extends HTMLInputElement {
static get observedAttributes() {
return ['value'];
}
constructor() {
super();
this.addEventListener("change", function (event) {
this.setAttribute('value', this.value);
});
}
connectedCallback() {
this.setAttribute('value', this.value);
}
attributeChangedCallback(name, oldValue, newValue) {
this.value = newValue;
}
}
我能够执行以下操作:
在输入中键入“test”
(tb.value && tb.value..attributes["value"])==="测试
通过改变属性值来改变属性
tb.attributes["value"].value ="test"-> tb.value ==="test"
但我不能执行以下操作:
tb.value = "test" -> tb.attributes["value"] === "test";
我认为解决方案是重写类的 get value() 和 set value(value) 。但我没有取得任何成功。
最佳答案
你不应该这样做,因为它会改变 <input>
的默认行为元素,这是来自 value
的单向绑定(bind)属性为value
属性。
无论如何,您需要重载 value
setter 和 getter 结合 super
,注意不要在两次更新中创建无限循环。
class TB extends HTMLInputElement {
static get observedAttributes() { return ['value'] }
constructor() {
super()
this.addEventListener( 'input', () => this.setAttribute( 'value', super.value ) )
}
attributeChangedCallback(name, oldValue, newValue) {
this.value = newValue
}
get value() { return super.value }
set value( val ) {
super.value = val
if ( val != this.getAttribute( 'value' ) )
this.setAttribute( 'value', val )
}
}
customElements.define( 'my-input', TB, { extends: 'input' } )
<input is="my-input" value="test" id=IN>
注意:这是一个简单的示例,未检查数据类型。
关于javascript - 在 native JavaScript 中双向反射(reflect)自定义 HTMLInput 元素中的属性和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944895/