diff --git a/2-ui/2-events/03-event-delegation/article.md b/2-ui/2-events/03-event-delegation/article.md index 41df9f079..9339c816a 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 -Capturing and bubbling allow us to implement one of most powerful event handling patterns called *event delegation*. +Capturing e bubbling ci permettono di implementare uno dei pattern più potenti nella gestione degli eventi, e cioè *event delegation*. -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. +Il concetto di base è che se abbiamo una serie di elementi gestiti in maniera simile, allora, invece di assegnare un gestore per ognuno di essi, possiamo metterne uno solo sui loro antenati comuni. -In the handler we get `event.target` to see where the event actually happened and handle it. +Nel gestore avremo a disposizione `event.target` per controllare l'elemento dal quale è partito l'evento e poterlo quindi gestire di conseguenza. -Let's see an example -- the [Ba-Gua diagram](http://en.wikipedia.org/wiki/Ba_gua) reflecting the ancient Chinese philosophy. +Guardiamo un esempio -- il [diagramma Ba-Gua](http://en.wikipedia.org/wiki/Ba_gua) che riflette l'antica filosofia Cinese. -Here it is: +Eccola qui: [iframe height=350 src="bagua" edit link] -The HTML is like this: +Questo è l'HTML: ```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 tabella è composta da 9 celle, ma potrebbero anche essercene 99 o 9999, è irrilevante. -**Our task is to highlight a cell `` on click.** +**Il nostro compito è quello di evidenziare un cella `` al click.** -Instead of assign an `onclick` handler to each `` (can be many) -- we'll setup the "catch-all" handler on `` element. +Invece di assegnare un gestore all'`onclick` per ogni `
` (potrebbero essercene tantissime) -- andiamo a impostare un gestore che sarà in grado di "catturali tutti" sull'elemento ``. -It will use `event.target` to get the clicked element and highlight it. +Verrà utilizzato `event.target` per ottenere l'elemento cliccato ed evidenziarlo. -The code: +Ecco il codice: ```js let selectedTd; *!* table.onclick = function(event) { - let target = event.target; // where was the click? + let target = event.target; // dove e' stato il click? - if (target.tagName != 'TD') return; // not on TD? Then we're not interested + if (target.tagName != 'TD') return; // non era un TD? Allora non siamo interessati - highlight(target); // highlight it + highlight(target); // evidenzialo }; */!* function highlight(td) { - if (selectedTd) { // remove the existing highlight if any + if (selectedTd) { // rimuove l'evidenziazione esistente, se presente selectedTd.classList.remove('highlight'); } selectedTd = td; - selectedTd.classList.add('highlight'); // highlight the new td + selectedTd.classList.add('highlight'); // evidenzia il nuovo 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. +Con un codice del genere non importa quante celle ci sono nella tabella. Possiamo aggiungere e rimuovere `` dinamicamente in qualunque momento e l'evidenziazione continuerà a funzionare. -Still, there's a drawback. +Ma abbiamo ancora un inconveniente. -The click may occur not on the ``, but inside it. +Il click potrebbe avvenire non sul ``, ma in un elemento interno. -In our case if we take a look inside the HTML, we can see nested tags inside ``, like ``: +Nel nostro cosa se osserviamo dentro l'HTML, possiamo vedere dei tags annidati dentro il ``, come ad esempio ``: ```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, se cliccassimo su questo `` proprio questo sarebbe il valore assunto da `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. +Nel gestore `table.onclick`, dovremmo perndere questo `event.target` e scoprire se il click sia avvenuto dentro il `` oppure no. -Here's the improved code: +Ecco il codice migliorato: ```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. +Chiarimenti: +1. Il metodo `elem.closest(selector)` ritorna l'antenato più vicino che combacia con il selettore. Nel nostro caso cerchiamo un `` verso l'alto dall'elemento di origine dell'evento. +2. Se `event.target` non è dentro nessun ``, la chiamata esce immediatamente, dal momento che non c'è nulla da fare. +3. Ne caso di tabelle annidate, `event.target` potrebbe riferirsi ad ``, ma fuori dalla tabelle corrente. Quindi andiamo a controllare se `` appartiene alla *nostra tabella*. +4. E se così, la evidenziamo. -As the result, we have a fast, efficient highlighting code, that doesn't care about the total number of `` in the table. +Come risultato, averemo un codice di evidenziazione veloce ed efficiente, indipendente dal numero di `` nella tabella. -## Delegation example: actions in markup +## Esempio di delegation: azioni nel markup -There are other uses for event delegation. +Esistono altri utilizzi per l'event delegation. -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? +Poniamo il caso che volessimo fare un menù con i pulsanti "Save", "Load", "Search" e cosi via, e che vi sia un oggetto con i metodi `save`, `load`, `search`... Come potremmo distinguerli? -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 prima idea potrebbe essere quella di assegnare dei gestori separati per ogni pulsante. Esiste però una soluzione più elegante. Possiamo aggiungere un gestore per l'intero menù e degli attributi `data-action` per i pulsanti che devono chiamare il metodo: ```html - + ``` -The handler reads the attribute and executes the method. Take a look at the working example: +Il gestore legge l'attributo ed esegue il metodo. Diamo uno sguardo all'esempio: ```html autorun height=60 run untrusted