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..4ac229cfd 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 @@ +Observe: -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. +1. Limpamos o timer `setInterval` quando o elemento é removido do documento. Isso é importante, caso contrário ele continua atualizando mesmo que não seja mais necessário. E o navegador não consegue limpar a memória deste elemento e referenciados por ele. +2. Podemos acessar a data atual como propriedade `elem.date`. Todos os métodos e propriedades da classe são naturalmente métodos e propriedades do 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..79e03c689 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 deixar o elemento ser coletado como lixo } } 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..e9d8206f7 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..fb2a0d11e 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 */ + /* Seu código aqui */ } 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..8efd60f78 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,20 +1,20 @@ +# Elemento timer ao vivo -# Live timer element +Já temos o elemento `` para mostrar um tempo bem formatado. -We already have `` element to show a nicely formatted time. +Crie o elemento `` para mostrar o tempo atual: -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 ). +1. Ele deve usar `` internamente, não duplicar sua funcionalidade. +2. Atualiza a cada segundo. +3. Para cada atualização, um evento customizado chamado `tick` deve ser gerado, com a data atual em `event.detail` (veja o capítulo ). -Usage: +Uso: ```html ``` diff --git a/8-web-components/2-custom-elements/article.md b/8-web-components/2-custom-elements/article.md index a84ed1192..8a2e59b4f 100644 --- a/8-web-components/2-custom-elements/article.md +++ b/8-web-components/2-custom-elements/article.md @@ -1,81 +1,83 @@ +# Elementos customizados -# Custom elements +Podemos criar elementos HTML customizados, descritos por nossa classe, com seus próprios métodos e propriedades, eventos e assim por diante. -We can create custom HTML elements, described by our class, with its own methods and properties, events and so on. +Uma vez que um elemento customizado é definido, podemos usá-lo em paridade com elementos HTML nativos. -Once a custom element is defined, we can use it on par with built-in HTML elements. +Isso é ótimo, pois o dicionário HTML é rico, mas não infinito. Não existem ``, ``, ``... Pense em qualquer outra tag que possamos precisar. -That's great, as HTML dictionary is rich, but not infinite. There are no ``, ``, ``... Just think of any other tag we might need. +Podemos defini-los com uma classe especial, e então usá-los como se sempre fizessem parte do HTML. -We can define them with a special class, and then use as if they were always a part of HTML. +Existem dois tipos de elementos customizados: -There are two kinds of custom elements: +1. **Elementos customizados autônomos** -- elementos "completamente novos", estendendo a classe abstrata `HTMLElement`. +2. **Elementos nativos customizados** -- estendendo elementos nativos, como um botão customizado, baseado em `HTMLButtonElement` etc. -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. +Primeiro vamos cobrir elementos autônomos, e depois passar para os elementos nativos customizados. -First we'll cover autonomous elements, and then move to customized built-in ones. +Para criar um elemento customizado, precisamos informar ao navegador vários detalhes sobre ele: como mostrá-lo, o que fazer quando o elemento é adicionado ou removido da página, etc. -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. +Isso é feito criando uma classe com métodos especiais. É fácil, pois há apenas alguns métodos, e todos eles são opcionais. -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. - -Here's a sketch with the full list: +Aqui está um esboço com a lista completa: ```js class MyElement extends HTMLElement { constructor() { super(); - // element created + // elemento criado } 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) + // o navegador chama este método quando o elemento é adicionado ao documento + // (pode ser chamado muitas vezes se um elemento for repetidamente adicionado/removido) } 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) + // o navegador chama este método quando o elemento é removido do documento + // (pode ser chamado muitas vezes se um elemento for repetidamente adicionado/removido) } static get observedAttributes() { - return [/* array of attribute names to monitor for changes */]; + return [ + /* array de nomes de atributos para monitorar mudanças */ + ]; } attributeChangedCallback(name, oldValue, newValue) { - // called when one of attributes listed above is modified + // chamado quando um dos atributos listados acima é modificado } adoptedCallback() { - // called when the element is moved to a new document - // (happens in document.adoptNode, very rarely used) + // chamado quando o elemento é movido para um novo documento + // (acontece em document.adoptNode, muito raramente usado) } - // there can be other element methods and properties + // pode haver outros métodos e propriedades do elemento } ``` -After that, we need to register the element: +Depois disso, precisamos registrar o elemento: ```js -// let the browser know that is served by our new class +// deixe o navegador saber que é servido por nossa nova classe 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. +Agora para qualquer elemento HTML com tag ``, uma instância de `MyElement` é criada, e os métodos mencionados são chamados. Também podemos usar `document.createElement('my-element')` em JavaScript. -```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="Nome do elemento customizado deve conter um hífen `-`" +O nome do elemento customizado deve ter um hífen `-`, por exemplo `my-element`e`super-button`são nomes válidos, mas`myelement` não é. -That's to ensure that there are no name conflicts between built-in and custom HTML elements. -``` +Isso é para garantir que não haja conflitos de nomes entre elementos HTML nativos e customizados. + +```` -## Example: "time-formatted" +## Exemplo: "time-formatted" -For example, there already exists `