You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`MutationObserver`is a built-in object that observes a DOM element and fires a callback in case of changes.
4
+
Il `MutationObserver`è un oggetto incorporato (built-in object) che osserva un elemento DOM e lancia una callback in caso di variazioni.
5
5
6
-
We'll first see syntax, and then explore a real-world use case.
6
+
Prima di tutto vediamo la sintassi, dopodichè analizzaremo un un caso d'uso del mondo reale.
7
7
8
-
## Syntax
8
+
## Sintassi
9
9
10
-
`MutationObserver`is easy to use.
10
+
Il `MutationObserver`è semplice da usare.
11
11
12
-
First, we create an observer with a callback-function:
12
+
Come prima cosa, creiamo un observer con una funzione di callback:
13
13
14
14
```js
15
15
let observer =newMutationObserver(callback);
16
16
```
17
17
18
-
And then attach it to a DOM node:
18
+
quindi lo andiamo ad associare ad un nodo del DOM:
19
19
20
20
```js
21
21
observer.observe(node, config);
22
22
```
23
23
24
-
`config`is an object with boolean options "what kind of changes to react on":
25
-
-`childList` -- changes in the direct children of`node`,
26
-
-`subtree` -- in all descendants of`node`,
27
-
-`attributes` -- attributes of`node`,
28
-
-`attributeFilter` -- an array of attribute names, to observe only selected ones.
29
-
-`characterData` -- whether to observe`node.data` (text content),
24
+
`config`è un oggetto che indica delle informazioni del tipo "a quale tipo di variazioni reagire" del tipo:
25
+
-`childList` -- cambiamenti nei nodi figli (childrens) di`node`,
26
+
-`subtree` -- in tutti i nodi discendenti di`node`,
27
+
-`attributes` -- attributi di`node`,
28
+
-`attributeFilter` -- un array di attributi, per osservare solo quelli selezionati.
29
+
-`characterData` -- se bisogna osservare`node.data` (text content),
30
30
31
-
Few other options:
32
-
-`attributeOldValue` -- if `true`, pass both the old and the new value of attribute to callback (see below), otherwise only the new one (needs `attributes` option),
33
-
-`characterDataOldValue` -- if `true`, pass both the old and the new value of `node.data`to callback (see below), otherwise only the new one (needs `characterData` option).
31
+
Poche altre opzioni:
32
+
-`attributeOldValue` -- se impostato a `true`, passerà alla callback sia il vecchio che il nuovo valore dell'attributo (più informazioni in basso), altrimenti (`false`) passerà solamente il nuovo valore (necessita dell'opzione `attributes`).
33
+
-`characterDataOldValue` -- se impostato a `true`, passerà alla callback sia il vecchio che il nuovo valore di `node.data`(più informazioni in basso), altrimenti (`false`) passerà solamente il nuovo valore (necessita dell'opzione `characterData`).
34
34
35
-
Then after any changes, the`callback`is executed: changes are passed in the first argument as a list of [MutationRecord](https://dom.spec.whatwg.org/#mutationrecord) objects, and the observer itself as the second argument.
35
+
Quindi, dopo ogni variazione, la`callback`verrà eseguita: le variazioni vengono passate nel primo argomento come una lista di oggetti [MutationRecord](https://dom.spec.whatwg.org/#mutationrecord), e l'observer stesso come secondo argomento.
36
36
37
-
[MutationRecord](https://dom.spec.whatwg.org/#mutationrecord) objects have properties:
37
+
Gli oggetti [MutationRecord](https://dom.spec.whatwg.org/#mutationrecord) objects hanno proprietà:
38
38
39
-
-`type` -- mutation type, one of
40
-
-`"attributes"`: attribute modified
41
-
-`"characterData"`: data modified, used for text nodes,
42
-
-`"childList"`: child elements added/removed,
43
-
-`target` -- where the change occurred: an element for`"attributes"`, or text node for`"characterData"`, or an element for a`"childList"` mutation,
44
-
-`addedNodes/removedNodes` -- nodes that were added/removed,
45
-
-`previousSibling/nextSibling` -- the previous and next sibling to added/removed nodes,
46
-
-`attributeName/attributeNamespace` -- the name/namespace (for XML) of the changed attribute,
47
-
-`oldValue` -- the previous value, only for attribute or text changes, if the corresponding option is set`attributeOldValue`/`characterDataOldValue`.
39
+
-`type` -- tipo di mutation, uno tra:
40
+
-`"attributes"`: attributi modificati
41
+
-`"characterData"`: dati modificati, utilizzati per i nodi testuali,
42
+
-`"childList"`: elementi figlio aggiunti/rimossi,
43
+
-`target` -- dove la variazione è avvenuta: un elemento per`"attributes"`, o nodo testuale per`"characterData"`, o un elemento per un`"childList"` mutation,
44
+
-`addedNodes/removedNodes` -- nodi che sono stati aggiunti/rimossi,
45
+
-`previousSibling/nextSibling` -- il nodo di pari livello precedente e successivo rispetto al nodo aggiunto/rimosso,
46
+
-`attributeName/attributeNamespace` -- il nome/spazio dei nomi (name/namespace) (per XML) dell'attributo variato,
47
+
-`oldValue` -- il valore precedente, solo per variazioni di attributi o di testo, se è settata la relativa opzione`attributeOldValue`/`characterDataOldValue`.
48
48
49
-
For example, here's a`<div>`with `contentEditable` attribute. That attribute allows us to focus on it and edit.
49
+
Per esempio, abbiamo un`<div>`con un attributo `contentEditable`. Questo attributo ci permette di mettere il focus su di esso per poterlo modificare.
50
50
51
51
```html run
52
-
<divcontentEditableid="elem">Click and <b>edit</b>, please</div>
52
+
<divcontentEditableid="elem">Clicca e <b>modifica</b>, per piacere.</div>
53
53
54
54
<script>
55
55
let observer =newMutationObserver(mutationRecords=> {
Now if we change the text inside `<b>edit</b>`, we'll get a single mutation:
68
+
Adesso, se noi andiamo a modificare il testo all'interno di `<b>modifica</b>`, otterremo una sola mutation (single mutation):
69
69
70
70
```js
71
71
mutationRecords = [{
@@ -75,8 +75,7 @@ mutationRecords = [{
75
75
// other properties empty
76
76
}];
77
77
```
78
-
79
-
If we select and remove the `<b>edit</b>` altogether, we'll get multiple mutations:
78
+
Se invece selezioniamo e rimuoviamo del tutto `<b>modifica</b>`, otterremo una più mutation (multiple mutations):
80
79
81
80
```js
82
81
mutationRecords = [{
@@ -85,72 +84,72 @@ mutationRecords = [{
85
84
removedNodes: [<b>],
86
85
nextSibling:<text node>,
87
86
previousSibling:<text node>
88
-
//other properties empty
87
+
//altre proprieta' vuote
89
88
}, {
90
89
type:"characterData"
91
90
target:<text node>
92
-
// ...mutation details depend on how the browser handles such removal
93
-
//it may coalesce two adjacent text nodes "edit " and ", please" into one node
94
-
//or it may leave them separate text nodes
91
+
// ...i dettagli della mutation dipendono da come il browser implementa questa rimozione
92
+
//potrebbe fondere i due nodi adiacenti "modifica " e ", per piacere" in un nodo
93
+
//oppure potrebbe lasciarli in due nodi testuali separati
95
94
}];
96
95
```
97
96
98
-
So, `MutationObserver`allows to react on any changes within DOM subtree.
97
+
Quindi, `MutationObserver`permette di reagire a qualunqe variazione all'interno degli sottonodi del DOM.
99
98
100
-
## Usage for integration
99
+
## Utilizzo per l'integrazione
101
100
102
-
When such thing may be useful?
101
+
Quando questa cosa può essere utile?
103
102
104
-
Imagine the situation when you attach a third-party script that adds useful functionality on the page, but also does something unwanted, e.g. shows ads`<div class="ads">Unwanted ads</div>`.
103
+
Immagina la situazione in cui devi inserire uno script di terze parti che aggiunge delle funzionalità utili nella pagina, ma anche che faccia qualcosa di non richiesto, ad esempio, che mostri delle pubblicità`<div class="ads">Unwanted ads</div>`.
105
104
106
-
Naturally, the third-party script provides no mechanisms to remove it.
105
+
Ovviamente, lo script di terze parti non fornisce alcun meccanismo per rimuoverla.
107
106
108
-
Using `MutationObserver`, we can detect when such element appears in our DOM and remove it. While leaving the useful functionality intact. Surely though, creators of that script won't be happy that you took their useful stuff and removed the ads.
107
+
Utilizzando i `MutationObserver`, possiamo rilevare quando questi elementi si aggiungono al nostro DOM e rimuoverli. Lasciando però la funzionalità utile intatta. Tuttavia, quasi sicuramente, i creatori di questo script non sarebbero felici che prendiamo le funzioni utili e rimuoviamo le pubblicità.
109
108
110
-
There are other situations when a third-party script adds something into our document, and we'd like to detect, when it happens, to adapt our page, dynamically resize something etc.
109
+
Ci sono altre situazioni nella quale uno script di terze parti aggiunge qualcosa nel nostro documento, e ci piacerebbe rilevarlo, ove questo succeda, per adattare la nostra pagina, ridimensionare dinamicamente qualcosa, etc.
111
110
112
-
`MutationObserver`can easily handle this.
111
+
Il `MutationObserver`può gestirlo facilmente.
113
112
114
-
## Usage for architecture
113
+
## Utilizzo per l'architettura
115
114
116
-
There are also situations when `MutationObserver`is good from architectural standpoint.
115
+
Ci sono anche delle situazioni in cui il `MutationObserver`è di utilità dal punto di vista architetturale.
117
116
118
-
Let's say we're making a website about programming. Naturally, articles and other materials may contain source code snippets.
117
+
Diciamo che stiamo creando un sito sulla programmazione. Naturalmente, gli articoli ed altro materiale può contenere dei frammenti di codice (snippets).
119
118
120
-
Such snippet in HTML markup looks like this:
119
+
Questi frammenti nel markup HTML appaiono in questa maniera:
121
120
122
121
```html
123
122
...
124
123
<preclass="language-javascript"><code>
125
-
// here's the code
124
+
// qui il codice
126
125
let hello = "world";
127
126
</code></pre>
128
127
...
129
128
```
130
129
131
-
Also we'll use a JavaScript highlighting library on our site, e.g. [Prism.js](https://prismjs.com/). A call to `Prism.highlightElem(pre)`examines the contents of such `pre`elements and adds into them special tags and styles for colored syntax highlighting, similar to what you see in examples here, at this page.
130
+
Utilizziamo anche una libreria di evidenziatura del codice Javascript, ad esempio [Prism.js](https://prismjs.com/). Una chiamata al metodo `Prism.highlightElem(pre)`esaminerà il contenuto di questo elemento `pre`e lo inserirà dentro dei tags specifici, generando degli stili CSS appositi per creare la colorazione dell'evidenziatura della sintassi, similmente a quello che puoi notare nell'esempio di questa pagina.
132
131
133
-
When exactly to run that highlighting method? We can do it on `DOMContentLoaded` event, or at the bottom of the page. At that moment we have DOM ready, can search for elements `pre[class*="language"]`and call `Prism.highlightElem`on them:
132
+
Quando esattamente eseguire questo metodo per l'evidenziatura? Possiamo farlo nell'evento `DOMContentLoaded`, oppure alla fine della pagina. Nel momento in cui abbiamo il DOM pronto, potrà effettuare la ricerca degli elementi `pre[class*="language"]`e chiamare il metodo `Prism.highlightElem`su di essi.
Everything's simple so far, right? There are `<pre>`code snippets in HTML, we highlight them.
139
+
Finora è tutto molto semplice, giusto? Ci sono degli frammenti di codice`<pre>`nell'HTML, e noi li coloriamo.
141
140
142
-
Now let's go on. Let's say we're going to dynamically fetch materials from a server. We'll study methods for that [later in the tutorial](info:fetch). For now it only matters that we fetch an HTML article from a webserver and display it on demand:
141
+
Adesso andiamo avanti. Diciamo che andiamo ad eseguire il "fetch" di materiale da un server. Studieremo questi metodi [più avanti nel tutorial](info:fetch). Per adesso importa solamente che noi eseguiamo una richiesta (utilizzando il metodo "fetch") di un articolo HTML da un webserver lo lo visualizziamo on demand:
143
142
144
143
```js
145
144
let article =/* fetch new content from server */
146
145
articleElem.innerHTML= article;
147
146
```
148
147
149
-
The new`article` HTML may contain code snippets. We need to call`Prism.highlightElem`on them, otherwise they won't get highlighted.
148
+
Il nuovo`article` HTML potrebbe contenere dei frammenti di codice. Abbiamo bisogno di chiamare`Prism.highlightElem`su di essi, altrimenti il loro codice non verrà evidenziato.
150
149
151
-
**Where and when to call `Prism.highlightElem`for a dynamically loaded article?**
150
+
**Dove e quando chiamare `Prism.highlightElem`per un articolo caricato dinamicamente?**
152
151
153
-
We could append that call to the code that loads an article, like this:
152
+
Potremmo accodare questa chiamata al codice che carica un articolo, così:
...But imagine, we have many places in the code where we load contents: articles, quizzes, forum posts. Do we need to put the highlighting call everywhere? That's not very convenient, and also easy to forget.
164
+
...Ma immaginiamo, abbiamo un sacco di punti nel codice nei quali carichiamo contenuti, articoli, quiz, messaggi di forum. Dovremmo mettere la chiamata per l'evidenziatura dovunque? Non sarebbe molto conveniente ed è anche facile dimenticare di farlo ogni volta.
166
165
167
-
And what if the content is loaded by a third-party module? E.g. we have a forum written by someone else, that loads contents dynamically, and we'd like to add syntax highlighting to it. No one likes to patch third-party scripts.
166
+
E che succederebbe, inoltre, se il contenuto venisse caricato da un modulo terze parti? Ad esempio, abbiamo un forum scritto da qualcuno altro, che carica contenuti dinamicamente, e ci piacerebbe aggiungergli l'evidenziatura del codice. A nessuno piace patchare script di terze parti.
168
167
169
-
Luckily, there's another option.
168
+
Fortunatamente, esiste un'altra opzione.
170
169
171
-
We can use`MutationObserver`to automatically detect when code snippets are inserted in the page and highlight them.
170
+
Possiamo usare il`MutationObserver`per rilevare automaticamente i frammenti di codice che vengono inseriti nella pagina ed evidenziarli.
172
171
173
-
So we'll handle the highlighting functionality in one place, relieving us from the need to integrate it.
172
+
In questo modo gestiamo la funzionalità di evidenziatura soltanto in un posto, liberandoci della necessità di integrarla.
174
173
175
-
### Dynamic highlight demo
174
+
### Demo di evidenziatura dinamica
176
175
177
-
Here's the working example.
176
+
Qui l'esempio funzionante.
178
177
179
-
If you run this code, it starts observing the element below and highlighting any code snippets that appear there:
178
+
Se esegui questo codice, comincerà osservando l'elemento sotto ed evidenziando qualunque frammento di codice che apparirà lì:
180
179
181
180
```js run
182
181
let observer =newMutationObserver(mutations=> {
183
182
184
183
for(let mutation of mutations) {
185
-
//examine new nodes, is there anything to highlight?
184
+
//esamina i nuovi nodi, c'e' qualcosa da evidenziare?
186
185
187
186
for(let node ofmutation.addedNodes) {
188
-
//we track only elements, skip other nodes (e.g. text nodes)
187
+
//teniamo traccia solo degli elementi, ignorando sugli altri nodi (ad esempio i nodi testuali)
189
188
if (!(node instanceofHTMLElement)) continue;
190
189
191
-
//check the inserted element for being a code snippet
190
+
//controlla che l'elemento inserito sia un frammento di codice (code snippet)
192
191
if (node.matches('pre[class*="language-"]')) {
193
192
Prism.highlightElement(node);
194
193
}
195
194
196
-
//or maybe there's a code snippet somewhere in its subtree?
195
+
//o forse c'e' un frammento di codice da qualche parte tra i suo nodi figlio?
Qui c'è un elemento HTML e JavaScript che lo riempie dinamicamente utilizzando `innerHTML`.
209
209
210
-
Here's HTML-element and JavaScript that dynamically fills it using `innerHTML`.
211
-
212
-
Please run the previous code (above, observes that element), and then the code below. You'll see how `MutationObserver` detects and highlights the snippet.
210
+
Esegui il codice precedente (sopra, osserverà quell'elemento), e poi il codice sotto. Vedrai come il `MutationObserver` rileverà ed evidenzierà il frammento.
213
211
214
212
<pid="highlight-demo"style="border: 1pxsolid#ddd">Демо-элемент с <code>id="highlight-demo"</code>, за которым следит код примера выше.</p>
215
213
216
-
The code below populates`innerHTML`. Please run the code above first, it will watch and highlight the new content:
214
+
Il codice sotto popolerà`innerHTML`. Esegui prima il codice sopra, il quale osserverà ed evidenzierà il nuovo contenuto:
217
215
218
216
```js run
219
217
let demoElem =document.getElementById('highlight-demo');
220
218
221
-
// dynamically insert content with code snippets
222
-
demoElem.innerHTML=`A code snippet is below:
219
+
//inserisce dinamicamente del contenuto con dei code snippets
220
+
demoElem.innerHTML=`Giù c'è un code snippet:
223
221
<preclass="language-javascript"><code> let hello = "world!"; </code></pre>
Ora abbiamo il `MutationObserver` che può tenere traccia di tutte le evidenzaiture negli elementi osservati oppure l'intero `document`. Possiamo aggiungere/rimuovere frammenti di codice nell'HTML senza doverci preoccupare di gestirli.
230
229
231
-
Now we have `MutationObserver` that can track all highlighting in observed elements or the whole `document`. We can add/remove code snippets in HTML without thinking about it.
232
-
233
-
## Additional methods
230
+
## Metodi addizionali
234
231
235
-
There's a method to stop observing the node:
232
+
C'è un metodo per interrompere l'osservazione del nodo:
236
233
237
-
-`observer.disconnect()` -- stops the observation.
234
+
-`observer.disconnect()` -- ferma l'osservazione.
238
235
239
-
Another method often used with it:
236
+
Un altro metodo utilizzato spesso insieme:
240
237
241
-
-`mutationRecords = observer.takeRecords()` -- gets a list of unprocessed mutation records, those that happened, but the callback did not handle them.
238
+
-`mutationRecords = observer.takeRecords()` -- ottiene una lista di mutation records non processati, quelli che sono avvenuti, ma che non sono stati gestiti dalla callback.
242
239
243
240
```js
244
-
//we'd like to stop tracking changes
241
+
//ci piacerebbe smettere di tenere traccia delle variazioni
245
242
observer.disconnect();
246
243
247
-
// it might have not yet handled some mutations
244
+
//potrebbe non avere ancora gestito alcune mutations
248
245
let mutationRecords =observer.takeRecords();
249
246
// process mutationRecords
250
247
```
251
248
252
249
## Garbage collection
253
250
254
-
Observers use weak references to nodes internally. That is: if a node is removed from DOM, and becomes unreachable, then it becomes garbage collected, an observer doesn't prevent that.
251
+
Gli observer utilizzano internamente dei riferimenti deboli ai nodi. Si tratta di questo: se un nodo viene rimosso dal DOM, diventando quindi irraggiungibile, allora diventa eliggibile per la garbage collection, e un observer certamente non lo previene.
255
252
256
-
## Summary
253
+
## Riassumendo
257
254
258
-
`MutationObserver`can react on changes in DOM: attributes, added/removed elements, text content.
255
+
I `MutationObserver`possono reagire alle variazioni nel DOM: attributi, elementi aggiunti/rimossi, contenuto testuale.
259
256
260
-
We can use it to track changes introduced by other parts of our code, as well as to integrate with third-party scripts.
257
+
Possiamo usarli per tenere traccia di modifiche introdotte da altre parti del nostro codice, così come quando integriamo script di terze parti.
261
258
262
-
`MutationObserver`can track any changes. The config "what to observe" options are used for optimizations, not to spend resources on unneeded callback invocations.
259
+
I `MutationObserver`possono tenere traccia di ogni variazione. Le opzioni di configurazione "cosa osservare" vengono utilizzate per le ottimizzazioni, non per impiegare risorse in invocazioni di callback non richieste.
0 commit comments