如何访问Web组件上的observedAttributes

问题描述 投票:0回答:1

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

static get observedAttributes() { return ['myAttribute']; }

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

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

class Bar extends Foo {
    static get observedAttributes() {
        return ['bar'];
    }
}

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

我觉得这里的难点在于获取父类的

observedAttributes
。因为如果是在同一个班级,你就可以像@javimovi提到的那样
Foo.observedAttributes

这里有一个 jsbin 可以玩。

谢谢!

javascript html ecmascript-6 web-component es6-class
1个回答
5
投票

找到了!:

constructor
可以使用:

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

使用之前提到的例子。

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

class Bar extends Foo {
  static get observedAttributes() {
    return ['bar'];
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.