如何将观察到的属性用于匿名类 /函数?

发布于 2025-02-04 13:14:03 字数 551 浏览 4 评论 0原文

我想在匿名类 /功能上注册自定义元素。但是我想知道如何将观察到的用于对象?

类版本。它的工作原理

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

版本匿名类/函数。它如何不起作用

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

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

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 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

司马昭之心 2025-02-11 13:14:03

您可以定义a static static =“ https://developer.mozilla.org/en-us/docs/web/javascript/reference/reference/functions/get” rel =“ nofollow noreferrer”> getter 在您的类表达式上在ES2015及更高版本中:

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

否则,如果您可以支持ES2022及以上,则可以创建a 公共静态字段(而不是getter):

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

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"];
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文