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
connectedCallbackcorre cuando entra al documento.observedAttributesgobiernaattributeChangedCallback.- El shadow DOM limita los estilos al componente.
Palabras clave y builtins usados aquí
Numberclassconstconstructorextendsifstaticsuperthis
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.
Paso 2 de 2 en Observar y dibujar; paso 10 de 13 en El navegador.