Search code examples
javascripthtmlecmascript-6web-componentes6-class

How to access observedAttributes on Web Components


So in Web Components you can use the attributeChangedCallback once you have specified attributes to observe using:

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

How can I list/access the observed attributes from within my sub class?

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

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

Is this somehow possible? Is there a getter for the observed attributes?

I think the difficulty here lies in getting the observedAttributes of the parent class. Because if it was on the same class, you could just Foo.observedAttributes as @javimovi mentioned.

Here is a jsbin to play with.

Thank you!


Solution

  • Found it!: The constructor can be used:

    Returns a reference to the Object constructor function that created the instance object

    Using the example mentioned before.

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