有没有办法观察自定义组件中的所有数据属性?

sup*_*ion 8 javascript arrays web-component

我正在尝试使用 vanilla javascript 构建一个自定义组件,该组件观察所有数据属性的变化,例如:

class MyComponent extends HTMLElement {

  static get observedAttributes () {
      return ["data-one","data-two","data-three",so forth...]
  }

}
Run Code Online (Sandbox Code Playgroud)

理论上,可以为该组件分配任意数量的数据属性,因此无法准确预测会有多少个数据属性,但每次分配新的数据属性时,我都需要该组件执行一些操作,有什么办法去做吧?必须将每个属性的具体名称放入“observedAttributes”返回的数组中似乎确实具有限制性

作为奖励,有没有什么方法可以观察没有特定名称但遵循特定模式的属性?(例如,它们与正则表达式字符串或类似的东西匹配)

作为额外的奖励,有没有办法观察所有属性?(我知道由于性能因素,他们使这不是默认行为,但如果需要的话,能够启用它仍然是件好事)

Moh*_*tta 1

确保您可以通过使用基于此的自定义元素回调之一来做到这一点

这是所有自定义元素生命周期回调

  • 你需要关注这个 attributeChangedCallback

    // 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);
    
    Run Code Online (Sandbox Code Playgroud)