示例工程 21-web-components

21-web-components/01-x-counter/x-counter.js

javascript · 1.8 KB

运行:21 · x-counter

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

// x-counter.js —— 带 Shadow DOM 的自定义元素
import { formatCount, nextCount, parseStep } from './main.js';
 
export class XCounter extends HTMLElement {
  static observedAttributes = ['step'];
 
  #count = 0;
  #step = 1;
 
  constructor() {
    super();
    this.attachShadow({ mode: 'open' }).innerHTML = `
      <style>
        :host { display: inline-flex; gap: 4px; align-items: center; }
        button { min-width: 32px; }
      </style>
      <button type="button" data-action="dec" part="dec">-</button>
      <span part="value">0</span>
      <button type="button" data-action="inc" part="inc">+</button>
    `;
  }
 
  connectedCallback() {
    if (!this.hasAttribute('role')) this.setAttribute('role', 'group');
    this.shadowRoot.addEventListener('click', this.#onClick);
    this.#render();
  }
 
  disconnectedCallback() {
    this.shadowRoot.removeEventListener('click', this.#onClick);
  }
 
  attributeChangedCallback(name, _oldValue, newValue) {
    if (name === 'step') this.#step = parseStep(newValue);
    this.#render();
  }
 
  get count() {
    return this.#count;
  }
 
  #onClick = (event) => {
    const button = event.target.closest('button');
    if (!button) return;
    const delta = button.dataset.action === 'inc' ? this.#step : -this.#step;
    this.#count = nextCount(this.#count, delta);
    this.#render();
    this.dispatchEvent(
      new CustomEvent('count-change', {
        detail: { count: this.#count },
        bubbles: true,
        composed: true,
      }),
    );
  };
 
  #render() {
    const value = this.shadowRoot?.querySelector('[part="value"]');
    if (value) value.textContent = formatCount(this.#count);
  }
}
 
if (typeof customElements !== 'undefined' && !customElements.get('x-counter')) {
  customElements.define('x-counter', XCounter);
}