typestar

Un elemento personalizado en JavaScript

Tu propia etiqueta, con shadow DOM y callbacks de ciclo de vida.

class StarRating extends HTMLElement {
  static observedAttributes = ["stars"];

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
  }

  connectedCallback() {
    this.render();
  }

  attributeChangedCallback(name, previous, next) {
    if (previous !== next) this.render();
  }

  render() {
    const stars = Number(this.getAttribute("stars") ?? 0);
    this.shadowRoot.innerHTML = `
      <style>:host { color: rebeccapurple; }</style>
      <span>${"*".repeat(stars)}${".".repeat(3 - stars)}</span>
    `;
  }
}

customElements.define("star-rating", StarRating);

Cómo funciona

  1. connectedCallback corre cuando entra al documento.
  2. observedAttributes gobierna attributeChangedCallback.
  3. El shadow DOM limita los estilos al componente.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
26
Caracteres a escribir
532
Tokens
125
Ritmo de tres estrellas
105 tpm

Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 71 segundos.

Escribe este fragmento

Paso 2 de 2 en Observar y dibujar; paso 10 de 13 en El navegador.

← Anterior Siguiente →