From c8f74ca200bd1151abe6a3dc8de93e5f301376a8 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Fri, 19 Mar 2021 16:55:51 -0300 Subject: [PATCH 01/14] Custom elements --- .../1-live-timer/solution.md | 6 +- .../1-live-timer/solution.view/live-timer.js | 2 +- .../1-live-timer/source.view/index.html | 4 +- .../1-live-timer/source.view/live-timer.js | 2 +- .../2-custom-elements/1-live-timer/task.md | 14 +- 8-web-components/2-custom-elements/article.md | 201 +++++++++--------- 6 files changed, 114 insertions(+), 115 deletions(-) diff --git a/8-web-components/2-custom-elements/1-live-timer/solution.md b/8-web-components/2-custom-elements/1-live-timer/solution.md index a9eacc880..0a2f40cad 100644 --- a/8-web-components/2-custom-elements/1-live-timer/solution.md +++ b/8-web-components/2-custom-elements/1-live-timer/solution.md @@ -1,4 +1,4 @@ -Please note: -1. We clear `setInterval` timer when the element is removed from the document. That's important, otherwise it continues ticking even if not needed any more. And the browser can't clear the memory from this element and referenced by it. -2. We can access current date as `elem.date` property. All class methods and properties are naturally element methods and properties. +Por favor ten en cuenta: +1. Borramos el temporizador `setInterval` cuando el elemento es quitado del documento. Esto es importante, de otro modo continuará ejecutando aunque no se lo necesite más. Y el navegador no puede liberar la memoria asignada a este elemento. +2. Podemos acceder a la fecha actual con una propiedad `elem.date`. Todos los métodos de clase y propiedades son naturalmente métodos y propiedades del elemento. diff --git a/8-web-components/2-custom-elements/1-live-timer/solution.view/live-timer.js b/8-web-components/2-custom-elements/1-live-timer/solution.view/live-timer.js index a53d72e00..4b5e1e2ab 100644 --- a/8-web-components/2-custom-elements/1-live-timer/solution.view/live-timer.js +++ b/8-web-components/2-custom-elements/1-live-timer/solution.view/live-timer.js @@ -24,7 +24,7 @@ class LiveTimer extends HTMLElement { } disconnectedCallback() { - clearInterval(this.timer); // important to let the element be garbage-collected + clearInterval(this.timer); // importante para hacer el elemento disponible al recolector de basura } } diff --git a/8-web-components/2-custom-elements/1-live-timer/source.view/index.html b/8-web-components/2-custom-elements/1-live-timer/source.view/index.html index 878120241..1bb4be8e7 100644 --- a/8-web-components/2-custom-elements/1-live-timer/source.view/index.html +++ b/8-web-components/2-custom-elements/1-live-timer/source.view/index.html @@ -1,8 +1,8 @@ - + - + diff --git a/8-web-components/2-custom-elements/1-live-timer/source.view/live-timer.js b/8-web-components/2-custom-elements/1-live-timer/source.view/live-timer.js index e2fe2b69f..6e46b8bc4 100644 --- a/8-web-components/2-custom-elements/1-live-timer/source.view/live-timer.js +++ b/8-web-components/2-custom-elements/1-live-timer/source.view/live-timer.js @@ -1,6 +1,6 @@ class LiveTimer extends HTMLElement { - /* your code here */ + /* tu código aquí */ } diff --git a/8-web-components/2-custom-elements/1-live-timer/task.md b/8-web-components/2-custom-elements/1-live-timer/task.md index 1feb7490a..bef40f7cf 100644 --- a/8-web-components/2-custom-elements/1-live-timer/task.md +++ b/8-web-components/2-custom-elements/1-live-timer/task.md @@ -1,14 +1,14 @@ -# Live timer element +# Elemento reloj vivo -We already have `` element to show a nicely formatted time. +Ya tenemos un elemento `` para mostrar la hora agradablemente formateada. -Create `` element to show the current time: -1. It should use `` internally, not duplicate its functionality. -2. Ticks (updates) every second. -3. For every tick, a custom event named `tick` should be generated, with the current date in `event.detail` (see chapter ). +Crea el elemento `` para mostrar la hora actual: +1. Internamente debe usar ``, no duplicar su funcionalidad. +2. Aactualiza (¡tic!) cada segundo. +3. Por cada tic, un evento personalizado llamado `tick` debe ser generado, con la fecha actual en `event.detail` (ver artículo ). -Usage: +Uso: ```html diff --git a/8-web-components/2-custom-elements/article.md b/8-web-components/2-custom-elements/article.md index d77ba84ab..a741c5c94 100644 --- a/8-web-components/2-custom-elements/article.md +++ b/8-web-components/2-custom-elements/article.md @@ -1,81 +1,81 @@ -# Custom elements +# Elementos personalizados -We can create custom HTML elements, described by our class, with its own methods and properties, events and so on. +Podemos crear elementos HTML personalizados, descritos por nuestra clase, con sus propios métodos, propiedades, eventos y demás. -Once a custom element is defined, we can use it on par with built-in HTML elements. +Una vez que el elemento personalizado es definido, podemos usarlo a la par con los elementos HTML incorporados. -That's great, as HTML dictionary is rich, but not infinite. There are no ``, ``, ``... Just think of any other tag we might need. +Esto es grandioso, porque el el diccionario HTML es rico, pero no infinito. No hay ``, ``, ``... Solo piensa en cualquier otra etiqueta que puedas necesitar. -We can define them with a special class, and then use as if they were always a part of HTML. +Podemos definirlos con una clase especial, y luego usarlos como si siempre hubieran sido parte del HTML. -There are two kinds of custom elements: +Hay dos clases de elementos personalizados: -1. **Autonomous custom elements** -- "all-new" elements, extending the abstract `HTMLElement` class. -2. **Customized built-in elements** -- extending built-in elements, like a customized button, based on `HTMLButtonElement` etc. +1. **Elementos personalizados autónomos** -- elementos "todo-nuevo", extendiendo la clase `HTMLElement` abstracta. +2. **Elementos incorporados personalizados** -- extendiendo elementos incorporados, como un botón personalizado basado en `HTMLButtonElement`, etc. -First we'll cover autonomous elements, and then move to customized built-in ones. +Primero cubriremos los elementos autónomos, luego pasaremos a la personalización de elementos incorporados. -To create a custom element, we need to tell the browser several details about it: how to show it, what to do when the element is added or removed to page, etc. +Para crear un elemento personalizado, necesitamos decirle al navegador varios detalles acerca de él: cómo mostrarlo, qué hacer cuando el elemento es agregado o quitado de la página, etc. -That's done by making a class with special methods. That's easy, as there are only few methods, and all of them are optional. +Eso se logra creando una clase con métodos especiales. Es fácil, son solo unos pocos métodos y todos ellos son opcionales. -Here's a sketch with the full list: +Aquí el esquema con la lista completa: ```js class MyElement extends HTMLElement { constructor() { super(); - // element created + // elemento creado } connectedCallback() { - // browser calls this method when the element is added to the document - // (can be called many times if an element is repeatedly added/removed) + // el navegador llama a este método cuando el elemento es agregado al documento + // (puede ser llamado varias veces si un elemento es agregado/quitado repetidamente) } disconnectedCallback() { - // browser calls this method when the element is removed from the document - // (can be called many times if an element is repeatedly added/removed) + // el navegador llama a este método cuando el elemento es quitado del documento + // (puede ser llamado varias veces si un elemento es agregado/quitado repetidamente) } static get observedAttributes() { - return [/* array of attribute names to monitor for changes */]; + return [/* array de nombres de atributos para monitorear cambios */]; } attributeChangedCallback(name, oldValue, newValue) { - // called when one of attributes listed above is modified + // llamado cuando uno de los atributos listados arriba es modificado } adoptedCallback() { - // called when the element is moved to a new document - // (happens in document.adoptNode, very rarely used) + // llamado cuando el elemento es movido a un nuevo documento + // (ocurre en document.adoptNode, muy raramente usado) } - // there can be other element methods and properties + // puede haber otros métodos y propiedades de elemento } ``` -After that, we need to register the element: +Después de ello, necesitamos registrar el elemento: ```js -// let the browser know that is served by our new class +// hacer que el navegador conozca que es servido por nuestra nueva clase customElements.define("my-element", MyElement); ``` -Now for any HTML elements with tag ``, an instance of `MyElement` is created, and the aforementioned methods are called. We also can `document.createElement('my-element')` in JavaScript. +Ahora, para cualquier elemento HTML con la etiqueta ``, una instancia de`MyElement` es creada, y los métodos mencionados son llamados. También podemos crearlo con JavaScript: `document.createElement('my-element')`. -```smart header="Custom element name must contain a hyphen `-`" -Custom element name must have a hyphen `-`, e.g. `my-element` and `super-button` are valid names, but `myelement` is not. +```smart header="Los elementos personalizados deben tener un guión `-`" +Los elemento personalizados deben tener un guión corto `-`. Por ejemplo, `my-element` y `super-button` son nombres válidos, pero `myelement` no lo es. -That's to ensure that there are no name conflicts between built-in and custom HTML elements. +Esto es para asegurar que no hay conflicto de nombres entre los elementos incorporados y los personalizados. ``` -## Example: "time-formatted" +## Ejemplo: "time-formatted" -For example, there already exists `