示例工程 30-web-components-types

30-web-components-types/04-observed-attributes/src/main.ts

typescript · 1.0 KB

运行:30 · observed-attributes

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

export class XGreeting extends HTMLElement {
  static observedAttributes = ['name'];
 
  connectedCallback(): void {
    this.#render(this.getAttribute('name') ?? 'world');
  }
 
  attributeChangedCallback(name: string, _old: string | null, next: string | null): void {
    if (name === 'name') {
      this.#render(next ?? 'world');
    }
  }
 
  #render(name: string): void {
    this.textContent = `Hi ${name}`;
  }
}
 
export function defineGreeting(): void {
  if (typeof customElements === 'undefined') throw new Error('本示例需要浏览器环境');
  if (!customElements.get('x-greeting')) {
    customElements.define('x-greeting', XGreeting);
  }
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  defineGreeting();
  const element = document.createElement('x-greeting');
  document.body.append(element);
  element.setAttribute('name', 'Ada');
  const lines = [element.textContent ?? '(empty)'];
  for (const line of lines) {
    log(line);
  }
  return lines;
}