← 中文资源

简体中文版本

自定义元素生命周期回调

注册自定义元素并用 connectedCallback 与 attributeChangedCallback 渲染内容:属性变化自动触发重绘,无需手动同步 DOM。

阅读英文原文

实现说明

逻辑集中在类 StatusBadge里。 顶层就这几处状态:badge。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 直接运行文件,输出会带上标签,比如 connected:、attribute changed:、rendered text:——输出的每一行都能指回产生它的那次调用。

常见问题

「自定义元素生命周期回调」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

核心语句

const status = this.getAttribute('status') ?? 'unknown';

代码示例

class StatusBadge extends HTMLElement {
  static observedAttributes = ['status'];

  connectedCallback() {
    this.render();
    console.log('connected:', this.getAttribute('status'));
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (oldValue !== newValue) {
      console.log('attribute changed:', name, oldValue, '->', newValue);
      this.render();
    }
  }

  render() {
    const status = this.getAttribute('status') ?? 'unknown';
    this.textContent = status.toUpperCase();
  }
}

customElements.define('status-badge', StatusBadge);

const badge = document.createElement('status-badge');
badge.setAttribute('status', 'ready');
document.body.append(badge);
badge.setAttribute('status', 'done');
console.log('rendered text:', badge.textContent);