如何访问 Web 组件上的 ObservedAttributes

chi*_*zui 4 html javascript web-component ecmascript-6 es6-class

因此,在 Web 组件中,一旦您指定了要观察的属性,您就可以使用attributeChangedCallback :

static get observedAttributes() { return ['myAttribute']; }
Run Code Online (Sandbox Code Playgroud)

如何从我的子类中列出/访问观察到的属性?

class Foo extends HTMLElement {
    connectedCallback() {
        console.log(this.observedAttributes); // <= undefined
    }
}

class Bar extends Foo {
    static get observedAttributes() {
        return ['bar'];
    }
}
Run Code Online (Sandbox Code Playgroud)

这有可能吗?是否有针对观察到的属性的吸气剂?

我认为这里的困难在于获取observedAttributes父类的。因为如果它在同一个班级,你就可以Foo.observedAttributes像@javimovi提到的那样。

这里有一个jsbin可以玩。

谢谢你!

chi*_*zui 7

找到了!: constructor 可以使用:

返回对创建实例对象的 Object 构造函数的引用

使用前面提到的例子。

class Foo extends HTMLElement {
  connectedCallback() {
    console.log(this.constructor.observedAttributes); // <= ['bar']
  }
}

class Bar extends Foo {
  static get observedAttributes() {
    return ['bar'];
  }
}
Run Code Online (Sandbox Code Playgroud)