Search code examples
javascriptweb-component

How can I use observedAttributes to an anonymous class / function?


I want to register a custom element with an anonymous class / function. But I wonder how to use the observedAttributes to the object?

Class Version. How it works

<my-el name="abc"></my-el>
class MyEl extends HTMLElement {...}
MyEl.observedAttributes = ["name"];

Version anonymous class/ function. How it does not work

window.customElements.define("my-el", class extends HTMLElement {...});

// how i can bind now?
MyEl.observedAttributes() // throws an error: ReferenceError: MyEl is not defined 

Solution

  • You can define a static getter on your class expression like so, which is supported in ES2015 and above:

    window.customElements.define("my-el", class extends HTMLElement {
      static get observedAttributes() {
        return ["name"];
      }
    });
    

    Otherwise, if you can support ES2022 and above, you can create a public static field (rather than a getter):

    window.customElements.define("my-el", class extends HTMLElement {
      static observedAttributes = ["name"];
    });