Maik Lowrey
Maik Lowrey

Reputation: 17566

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 

Upvotes: 0

Views: 134

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50759

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"];
});

Upvotes: 1

Related Questions