← 中文资源

简体中文版本

Custom Elements 声明式监听属性变更

用 customElements.define 与 observedAttributes 把 HTML 属性变成组件配置面,属性变更触发回调重渲染,标签名类型合并后 createElement 直接得到组件类型。

阅读英文原文

实现说明

全部实现位于 UserBadge。 演示用的数据放在这几个模块级绑定中:badge。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 演示输出是带标签的(badge renders:),每个操作都会留下自己的一行标注。

常见问题

「Custom Elements 声明式监听属性变更」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

核心语句

this.textContent = `${this.getAttribute('name') ?? 'anon'} · ${this.displayRole}`;
if (name === 'role') this.displayRole = next ?? 'guest';

代码示例

// Custom Elements: observedAttributes declares the config keys the component watches (its configuration surface),
// attributeChangedCallback reacts to each change
class UserBadge extends HTMLElement {
  static observedAttributes = ['name', 'role'];

  private displayRole = 'guest';

  connectedCallback(): void {
    this.render();
  }

  attributeChangedCallback(name: string, _oldValue: string | null, next: string | null): void {
    if (name === 'role') this.displayRole = next ?? 'guest';
    if (name === 'name') this.render();
  }

  private render(): void {
    this.textContent = `${this.getAttribute('name') ?? 'anon'} · ${this.displayRole}`;
  }
}

customElements.define('user-badge', UserBadge);

// Declaration merging makes querySelector/createElement('user-badge') return UserBadge directly
declare global {
  interface HTMLElementTagNameMap {
    'user-badge': UserBadge;
  }
}

export {};

const badge = document.createElement('user-badge');
badge.setAttribute('name', 'Ada');
badge.setAttribute('role', 'admin');
document.body.append(badge);
console.log('badge renders:', badge.textContent);