我有一个继承自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;
}
}
我能够做到以下几点:
(tb.value && tb.value..attributes["value"])==="test
tb.attributes["value"].value ="test" -> tb.value ==="test"
但我不能做到以下几点:
tb.value = "test" -> tb.attributes["value"] === "test";
我认为解决方案是覆盖类的get值()和设置值(值)。但我没有任何成功。
你不应该这样做,因为它会改变<input>
元素的默认行为,这是从value
属性到value
属性的单向绑定。
无论如何,你需要重载value
setter和getter与super
相结合,注意不要用2更新创建一个无限循环。
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>
注意:这是一个不检查数据类型的简单示例。