【发布时间】:2022-11-12 16:11:41
【问题描述】:
我的目标是动态设置observedAttributes,因此我的Web 组件将只查看遵循某种模式的属性,例如冒号(:attr) <my-element static="value1" :dynamic=${dynamic}/>
在这种情况下,<my-element> 应该只为属性 :dynamic 设置 observedAttributes
问题是static get observedAttributes() 在this 之前运行,在https://andyogo.github.io/custom-element-reactions-diagram/ 中进行了解释
所以这行不通
static get observedAttributes() {
return this.getAttributeNames().filter((item) => item.startsWith(':'));
}
当然也没有
constructor() {
super();
this._observedAttributes = this.getAttributeNames().filter((item) => item.startsWith(':'));
}
static get observedAttributes() {
return this._observedAttributes;
}
谢谢!
<!DOCTYPE html>
<body>
<my-element static="value1" :dynamic="value2" ></my-element>
<script>
class MyElement extends HTMLElement {
constructor() {
super();
this._observedAttributes= this.getAttributeNames().filter((item) => item.startsWith(':'));
console.log('observedAttributes',this._observedAttributes);
}
static get observedAttributes() {
return this._observedAttributes;
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(name, oldValue, newValue); //doesn't log anything
}
}
customElements.define("my-element", MyElement);
setTimeout(() => {
console.log('setting dynamic attribute. This should trigger attributeChangedCallback. But no.');
document.querySelector('my-element').setAttribute(':dynamic', 'value3');
}, 2000);
</script>
</body>
</html>
【问题讨论】:
-
然后,您需要一个 Web 组件来创建另一个 Web 组件(具有动态观察属性)
-
或使用 MutationObserver API
标签: javascript web-component native-web-component