diff --git a/2-ui/2-events/03-event-delegation/1-hide-message-delegate/task.md b/2-ui/2-events/03-event-delegation/1-hide-message-delegate/task.md index 62c0a8ab0..1b29127e2 100644 --- a/2-ui/2-events/03-event-delegation/1-hide-message-delegate/task.md +++ b/2-ui/2-events/03-event-delegation/1-hide-message-delegate/task.md @@ -2,12 +2,12 @@ importance: 5 --- -# Hide messages with delegation +# Ocultar mensajes con delegación -There's a list of messages with removal buttons `[x]`. Make the buttons work. +Hay una lista de mensajes con botones para borrarlos `[x]`. Haz que funcionen. -Like this: +Como esto: [iframe src="solution" height=420] -P.S. Should be only one event listener on the container, use event delegation. +P.D. Debe haber solamente un _event lintener_ en el contenedor, usa delegación de eventos. diff --git a/2-ui/2-events/03-event-delegation/2-sliding-tree/solution.md b/2-ui/2-events/03-event-delegation/2-sliding-tree/solution.md index 09c14a08c..2ef1d81c5 100644 --- a/2-ui/2-events/03-event-delegation/2-sliding-tree/solution.md +++ b/2-ui/2-events/03-event-delegation/2-sliding-tree/solution.md @@ -1,4 +1,4 @@ -The solution has two parts. +La solución tiene dos partes. -1. Wrap every tree node title into ``. Then we can CSS-style them on `:hover` and handle clicks exactly on text, because `` width is exactly the text width (unlike without it). -2. Set a handler to the `tree` root node and handle clicks on that `` titles. +1. Envuelve cada nodo de título del árbol dentro de ``. Luego podemos aplicarles CSS-style en `:hover` y manejar los clics exactamente sobre el texto, porque el ancho de `` es exactamente el ancho del texto (no lo será si no lo tiene). +2. Establece el manejador al nodo raíz del `tree` y maneja los clics en aquellos títulos ``. diff --git a/2-ui/2-events/03-event-delegation/2-sliding-tree/task.md b/2-ui/2-events/03-event-delegation/2-sliding-tree/task.md index bdcf2a510..42fdffa79 100644 --- a/2-ui/2-events/03-event-delegation/2-sliding-tree/task.md +++ b/2-ui/2-events/03-event-delegation/2-sliding-tree/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Tree menu +# Menú de árbol -Create a tree that shows/hides node children on click: +Crea un árbol que muestre y oculte nodos hijos con clics: [iframe border=1 src="solution"] -Requirements: +Requerimientos: -- Only one event handler (use delegation) -- A click outside the node title (on an empty space) should not do anything. +- Solamente un manejador de eventos (usa delegación) +- Un clic fuera de los nodos de títulos (en un espacio vacío) no debe hacer nada. diff --git a/2-ui/2-events/03-event-delegation/3-sortable-table/task.md b/2-ui/2-events/03-event-delegation/3-sortable-table/task.md index ec85a473c..e0f31505c 100644 --- a/2-ui/2-events/03-event-delegation/3-sortable-table/task.md +++ b/2-ui/2-events/03-event-delegation/3-sortable-table/task.md @@ -2,11 +2,11 @@ importance: 4 --- -# Sortable table +# Tabla ordenable -Make the table sortable: clicks on `` elements should sort it by corresponding column. +Haz que la tabla se pueda ordenar: los clics en elementos `` deberían ordenarla por la columna correspondiente. -Each `` has the type in the attribute, like this: +Cada `` tiene su tipo de datos en el atributo, como esto: ```html @@ -32,12 +32,12 @@ Each `
` has the type in the attribute, like this:
``` -In the example above the first column has numbers, and the second one -- strings. The sorting function should handle sort according to the type. +En el ejemplo anterior la primera columna tiene números y la segunda cadenas. La función de ordenamiento debe manejar el orden de acuerdo al tipo de dato. -Only `"string"` and `"number"` types should be supported. +Solamente los tipos `"string"` y `"number"` deben ser soportados. -The working example: +Ejemplo en funcionamiento: [iframe border=1 src="solution" height=190] -P.S. The table can be big, with any number of rows and columns. +P.D. La tabla puede ser grande, con cualquier cantidad de filas y columnas. diff --git a/2-ui/2-events/03-event-delegation/4-behavior-tooltip/task.md b/2-ui/2-events/03-event-delegation/4-behavior-tooltip/task.md index 3001b9915..ff50e6aa1 100644 --- a/2-ui/2-events/03-event-delegation/4-behavior-tooltip/task.md +++ b/2-ui/2-events/03-event-delegation/4-behavior-tooltip/task.md @@ -2,37 +2,37 @@ importance: 5 --- -# Tooltip behavior +# Comportamiento: Tooltip -Create JS-code for the tooltip behavior. +Crea código JS para el comportamiento "tooltip". -When a mouse comes over an element with `data-tooltip`, the tooltip should appear over it, and when it's gone then hide. +Cuando un mouse pasa sobre un elemento con `data-tooltip`, el tooltip debe aparecer sobre él, y ocultarse cuando se va. -An example of annotated HTML: +Un ejemplo en HTML comentado: ```html ``` -Should work like this: +Debe funcionar así: [iframe src="solution" height=200 border=1] -In this task we assume that all elements with `data-tooltip` have only text inside. No nested tags (yet). +En esta tarea suponemos que todos los elementos con `data-tooltip` solo tienen texto dentro. Sin tags anidados (todavía). -Details: +Detalles: -- The distance between the element and the tooltip should be `5px`. -- The tooltip should be centered relative to the element, if possible. -- The tooltip should not cross window edges. Normally it should be above the element, but if the element is at the page top and there's no space for the tooltip, then below it. -- The tooltip content is given in the `data-tooltip` attribute. It can be arbitrary HTML. +- La distancia entre el elemento y el tooltip debe ser `5px`. +- El tooltip debe ser centrado relativo al elemento si es posible. +- El tooltip no debe cruzar los bordes de la ventana. Normalmente debería estar sobre el elemento, pero si el elemento está en la parte superior de la página y no hay espacio para el tooltip, entonces debajo de él. +- El contenido del tooltip está dado en el atributo `data-tooltip`. Este puede ser HTML arbitrario. -You'll need two events here: -- `mouseover` triggers when a pointer comes over an element. -- `mouseout` triggers when a pointer leaves an element. +Necesitarás dos eventos aquí: +- `mouseover` se dispara cuando el puntero pasa sobre el elemento. +- `mouseout` se dispara cuando el puntero deja el elemento. -Please use event delegation: set up two handlers on `document` to track all "overs" and "outs" from elements with `data-tooltip` and manage tooltips from there. +Usa delegación de eventos: prepare dos manejadores en el `document` para rastrear todos los "overs" y "outs" de los elementos con `data-tooltip` y administra los tooltips desde allí. -After the behavior is implemented, even people unfamiliar with JavaScript can add annotated elements. +Después de implementar el comportamiento, incluso gente no familiarizada con JavaScript puede agregar elementos anotados. -P.S. Only one tooltip may show up at a time. +P.D. Solamente un tooltip puede mostrarse a la vez. diff --git a/2-ui/2-events/03-event-delegation/article.md b/2-ui/2-events/03-event-delegation/article.md index df086f24b..609709d9c 100644 --- a/2-ui/2-events/03-event-delegation/article.md +++ b/2-ui/2-events/03-event-delegation/article.md @@ -1,19 +1,19 @@ -# Event delegation +# Delegación de eventos -Capturing and bubbling allow us to implement one of most powerful event handling patterns called *event delegation*. +La captura y el propagación nos permiten implementar uno de los más poderosos patrones de manejo de eventos llamado *delegación de eventos*. -The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them -- we put a single handler on their common ancestor. +La idea es que si tenemos muchos elementos manejados de manera similar podemos, en lugar de asignar un manejador a cada uno de ellos, poner un único manejador a su ancestro común. -In the handler we get `event.target`, see where the event actually happened and handle it. +Del controlador obtenemos `event.target`, vemos dónde ocurrió realmente el evento y lo controlamos. -Let's see an example -- the [Ba-Gua diagram](http://en.wikipedia.org/wiki/Ba_gua) reflecting the ancient Chinese philosophy. +Veamos un ejemplo: El [diagrama Pa kua](https://es.wikipedia.org/wiki/Pa_kua) que refleja la antigua filosofía china. -Here it is: +Aquí está: [iframe height=350 src="bagua" edit link] -The HTML is like this: +El HTML es este: ```html @@ -30,45 +30,45 @@ The HTML is like this:
``` -The table has 9 cells, but there could be 99 or 9999, doesn't matter. +La tabla tiene 9 celdas, pero puede haber 99 o 999, eso no importa. -**Our task is to highlight a cell `` on click.** +**Nuestra tarea es destacar una celda `` al hacer clic en ella.** -Instead of assign an `onclick` handler to each `` (can be many) -- we'll setup the "catch-all" handler on `` element. +En lugar de asignar un manejador `onclick` a cada `
` (puede haber muchos), configuramos un manejador "atrapa-todo" en el elemento ``. -It will use `event.target` to get the clicked element and highlight it. +Este usará `event.target` para obtener el elemento del clic y destacarlo. -The code: +El código: ```js let selectedTd; *!* table.onclick = function(event) { - let target = event.target; // where was the click? + let target = event.target; // ¿dónde fue el clic? - if (target.tagName != 'TD') return; // not on TD? Then we're not interested + if (target.tagName != 'TD') return; // ¿no es un TD? No nos interesa - highlight(target); // highlight it + highlight(target); // destacarlo }; */!* function highlight(td) { - if (selectedTd) { // remove the existing highlight if any + if (selectedTd) { // quitar cualquier celda destacada que hubiera antes selectedTd.classList.remove('highlight'); } selectedTd = td; - selectedTd.classList.add('highlight'); // highlight the new td + selectedTd.classList.add('highlight'); // y destacar el nuevo td } ``` -Such a code doesn't care how many cells there are in the table. We can add/remove `
` dynamically at any time and the highlighting will still work. +A tal código no le interesa cuántas celdas hay en la tabla. Podemos agregar y quitar `` dinámicamente en cualquier momento y el realzado aún funcionará. -Still, there's a drawback. +Pero hay un inconveniente. -The click may occur not on the ``, but inside it. +El clic puede ocurrir no sobre ``, sino dentro de él. -In our case if we take a look inside the HTML, we can see nested tags inside ``, like ``: +En nuestro caso, si miramos dentro del HTML, podemos ver tags anidados dentro de ``, como ``: ```html @@ -79,13 +79,13 @@ In our case if we take a look inside the HTML, we can see nested tags inside ` ``` -Naturally, if a click happens on that `` then it becomes the value of `event.target`. +Naturalmente, si el clic ocurre en ``, este se vuelve el valor de `event.target`. ![](bagua-bubble.svg) -In the handler `table.onclick` we should take such `event.target` and find out whether the click was inside `` or not. +En el manejador `table.onclick` debemos tomar tal `event.target` e indagar si el clic fue dentro de `` o no. -Here's the improved code: +Aquí el código mejorado: ```js table.onclick = function(event) { @@ -99,27 +99,27 @@ table.onclick = function(event) { }; ``` -Explanations: -1. The method `elem.closest(selector)` returns the nearest ancestor that matches the selector. In our case we look for `` on the way up from the source element. -2. If `event.target` is not inside any ``, then the call returns immediately, as there's nothing to do. -3. In case of nested tables, `event.target` may be a ``, but lying outside of the current table. So we check if that's actually *our table's* ``. -4. And, if it's so, then highlight it. +Explicación: +1. El método `elem.closest(selector)` devuelve el ancestro más cercano que coincide con el selector. En nuestro caso buscamos `` hacia arriba desde el elemento de origen. +2. Si `event.target` no ocurrió dentro de algún ``, el llamado retorna inmediatamente pues no hay nada que hacer. +3. En caso de tablas anidadas, `event.target` podría ser un `` pero fuera de la tabla actual. Entonces verificamos que sea realmente un `` de *nuestra tabla*. +4. Y, si es así, destacarla. -As the result, we have a fast, efficient highlighting code, that doesn't care about the total number of `` in the table. +Como resultado, tenemos un código de realzado rápido y eficiente al que no le afecta la cantidad total de `` en la tabla. -## Delegation example: actions in markup +## Ejemplo de delegación: acciones en markup -There are other uses for event delegation. +Hay otros usos para la delegación de eventos. -Let's say, we want to make a menu with buttons "Save", "Load", "Search" and so on. And there's an object with methods `save`, `load`, `search`... How to match them? +Digamos que queremos hacer un menú con los botones "Save", "Load", "Search" y así. Y hay objetos con los métodos `save`, `load`, `search`... ¿Cómo asociarlos? -The first idea may be to assign a separate handler to each button. But there's a more elegant solution. We can add a handler for the whole menu and `data-action` attributes for buttons that has the method to call: +La primera idea podría ser asignar un controlador separado para cada botón. Pero hay una solución más elegante. Podemos agregar un controlador para el menú completo y un atributo `data-action` a los botones con el método a llamar: ```html ``` -The handler reads the attribute and executes the method. Take a look at the working example: +El manejador lee el atributo y ejecuta el método. Puedes ver el siguiente ejemplo en funcionamiento: ```html autorun height=60 run untrusted