我正在尝试使用 vanilla javascript 构建一个自定义组件,该组件观察所有数据属性的变化,例如:
class MyComponent extends HTMLElement {
static get observedAttributes () {
return ["data-one","data-two","data-three",so forth...]
}
}
这个组件理论上可以被分配任意数量的数据属性,所以没有办法准确预测会有多少个,但我需要组件在每次分配新的数据属性时做一些事情,有没有怎么办?必须将每个属性的具体名称放入“observedAttributes”返回的数组中似乎确实具有限制性
作为奖励,有没有什么方法可以观察没有特定名称但遵循特定模式的属性? (例如,它们与正则表达式字符串或类似的东西匹配)
还有一个额外的好处,有没有办法观察所有属性? (我知道由于性能因素,他们使这不是默认行为,但如果需要的话能够启用它仍然是件好事)
确保您可以通过使用基于 this 的自定义元素回调
之一来实现此目的这里是所有自定义元素生命周期回调
你需要关注这一点 属性更改回调
// Create a class for the element
class MyCustomElement extends HTMLElement {
static observedAttributes = ["color", "size"];
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
console.log("Custom element added to page.");
}
disconnectedCallback() {
console.log("Custom element removed from page.");
}
adoptedCallback() {
console.log("Custom element moved to new page.");
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`Attribute ${name} has changed.`);
}
}
customElements.define("my-custom-element", MyCustomElement);