Skip to content

Commit c8922e4

Browse files
authored
Merge pull request #114 from pierangelomiceli/patch-1
Update article.md
2 parents 86ada8e + 3f06cf4 commit c8922e4

File tree

1 file changed

+86
-89
lines changed

1 file changed

+86
-89
lines changed
Lines changed: 86 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,59 @@
11

22
# Mutation observer
33

4-
`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.
55

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.
77

8-
## Syntax
8+
## Sintassi
99

10-
`MutationObserver` is easy to use.
10+
Il `MutationObserver` è semplice da usare.
1111

12-
First, we create an observer with a callback-function:
12+
Come prima cosa, creiamo un observer con una funzione di callback:
1313

1414
```js
1515
let observer = new MutationObserver(callback);
1616
```
1717

18-
And then attach it to a DOM node:
18+
quindi lo andiamo ad associare ad un nodo del DOM:
1919

2020
```js
2121
observer.observe(node, config);
2222
```
2323

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),
3030

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`).
3434

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.
3636

37-
[MutationRecord](https://dom.spec.whatwg.org/#mutationrecord) objects have properties:
37+
Gli oggetti [MutationRecord](https://dom.spec.whatwg.org/#mutationrecord) objects hanno proprietà:
3838

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`.
4848

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.
5050

5151
```html run
52-
<div contentEditable id="elem">Click and <b>edit</b>, please</div>
52+
<div contentEditable id="elem">Clicca e <b>modifica</b>, per piacere.</div>
5353

5454
<script>
5555
let observer = new MutationObserver(mutationRecords => {
56-
console.log(mutationRecords); // console.log(the changes)
56+
console.log(mutationRecords); // console.log(le modifiche)
5757
});
5858
5959
// observe everything except attributes
@@ -65,7 +65,7 @@ observer.observe(elem, {
6565
</script>
6666
```
6767

68-
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):
6969

7070
```js
7171
mutationRecords = [{
@@ -75,8 +75,7 @@ mutationRecords = [{
7575
// other properties empty
7676
}];
7777
```
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&ugrave; mutation (multiple mutations):
8079

8180
```js
8281
mutationRecords = [{
@@ -85,72 +84,72 @@ mutationRecords = [{
8584
removedNodes: [<b>],
8685
nextSibling: <text node>,
8786
previousSibling: <text node>
88-
// other properties empty
87+
// altre proprieta' vuote
8988
}, {
9089
type: "characterData"
9190
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
9594
}];
9695
```
9796

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.
9998

100-
## Usage for integration
99+
## Utilizzo per l'integrazione
101100

102-
When such thing may be useful?
101+
Quando questa cosa pu&ograve; essere utile?
103102

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&agrave; utili nella pagina, ma anche che faccia qualcosa di non richiesto, ad esempio, che mostri delle pubblicit&agrave; `<div class="ads">Unwanted ads</div>`.
105104

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.
107106

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&ograve; la funzionalit&agrave; utile intatta. Tuttavia, quasi sicuramente, i creatori di questo script non sarebbero felici che prendiamo le funzioni utili e rimuoviamo le pubblicit&agrave;.
109108

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.
111110

112-
`MutationObserver` can easily handle this.
111+
Il `MutationObserver` pu&ograve; gestirlo facilmente.
113112

114-
## Usage for architecture
113+
## Utilizzo per l'architettura
115114

116-
There are also situations when `MutationObserver` is good from architectural standpoint.
115+
Ci sono anche delle situazioni in cui il `MutationObserver` &egrave; di utilit&agrave; dal punto di vista architetturale.
117116

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&ograve; contenere dei frammenti di codice (snippets).
119118

120-
Such snippet in HTML markup looks like this:
119+
Questi frammenti nel markup HTML appaiono in questa maniera:
121120

122121
```html
123122
...
124123
<pre class="language-javascript"><code>
125-
// here's the code
124+
// qui il codice
126125
let hello = "world";
127126
</code></pre>
128127
...
129128
```
130129

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&agrave; il contenuto di questo elemento `pre` e lo inserir&agrave; 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.
132131

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&agrave; effettuare la ricerca degli elementi `pre[class*="language"]` e chiamare il metodo `Prism.highlightElem` su di essi.
134133

135134
```js
136135
// highlight all code snippets on the page
137136
document.querySelectorAll('pre[class*="language"]').forEach(Prism.highlightElem);
138137
```
139138

140-
Everything's simple so far, right? There are `<pre>` code snippets in HTML, we highlight them.
139+
Finora &egrave; tutto molto semplice, giusto? Ci sono degli frammenti di codice`<pre>` nell'HTML, e noi li coloriamo.
141140

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&ugrave; 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:
143142

144143
```js
145144
let article = /* fetch new content from server */
146145
articleElem.innerHTML = article;
147146
```
148147

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&agrave; evidenziato.
150149

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?**
152151

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&igrave;:
154153

155154
```js
156155
let article = /* fetch new content from server */
@@ -162,38 +161,38 @@ snippets.forEach(Prism.highlightElem);
162161
*/!*
163162
```
164163

165-
...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 &egrave; anche facile dimenticare di farlo ogni volta.
166165

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.
168167

169-
Luckily, there's another option.
168+
Fortunatamente, esiste un'altra opzione.
170169

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.
172171

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&agrave; di evidenziatura soltanto in un posto, liberandoci della necessit&agrave; di integrarla.
174173

175-
### Dynamic highlight demo
174+
### Demo di evidenziatura dinamica
176175

177-
Here's the working example.
176+
Qui l'esempio funzionante.
178177

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&agrave; osservando l'elemento sotto ed evidenziando qualunque frammento di codice che apparir&agrave; l&igrave;:
180179

181180
```js run
182181
let observer = new MutationObserver(mutations => {
183182

184183
for(let mutation of mutations) {
185-
// examine new nodes, is there anything to highlight?
184+
// esamina i nuovi nodi, c'e' qualcosa da evidenziare?
186185

187186
for(let node of mutation.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)
189188
if (!(node instanceof HTMLElement)) continue;
190189

191-
// check the inserted element for being a code snippet
190+
// controlla che l'elemento inserito sia un frammento di codice (code snippet)
192191
if (node.matches('pre[class*="language-"]')) {
193192
Prism.highlightElement(node);
194193
}
195194

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?
197196
for(let elem of node.querySelectorAll('pre[class*="language-"]')) {
198197
Prism.highlightElement(elem);
199198
}
@@ -206,57 +205,55 @@ let demoElem = document.getElementById('highlight-demo');
206205

207206
observer.observe(demoElem, {childList: true, subtree: true});
208207
```
208+
Qui c'&egrave; un elemento HTML e JavaScript che lo riempie dinamicamente utilizzando `innerHTML`.
209209

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&agrave; quell'elemento), e poi il codice sotto. Vedrai come il `MutationObserver` rilever&agrave; ed evidenzier&agrave; il frammento.
213211

214212
<p id="highlight-demo" style="border: 1px solid #ddd">Демо-элемент с <code>id="highlight-demo"</code>, за которым следит код примера выше.</p>
215213

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&agrave; `innerHTML`. Esegui prima il codice sopra, il quale osserver&agrave; ed evidenzier&agrave; il nuovo contenuto:
217215

218216
```js run
219217
let demoElem = document.getElementById('highlight-demo');
220218

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&ugrave; c'&egrave; un code snippet:
223221
<pre class="language-javascript"><code> let hello = "world!"; </code></pre>
224-
<div>Another one:</div>
222+
<div>Un altro:</div>
225223
<div>
226224
<pre class="language-css"><code>.class { margin: 5px; } </code></pre>
227225
</div>
228226
`;
229227
```
228+
Ora abbiamo il `MutationObserver` che pu&ograve; 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.
230229

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
234231

235-
There's a method to stop observing the node:
232+
C'&egrave; un metodo per interrompere l'osservazione del nodo:
236233

237-
- `observer.disconnect()` -- stops the observation.
234+
- `observer.disconnect()` -- ferma l'osservazione.
238235

239-
Another method often used with it:
236+
Un altro metodo utilizzato spesso insieme:
240237

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.
242239

243240
```js
244-
// we'd like to stop tracking changes
241+
// ci piacerebbe smettere di tenere traccia delle variazioni
245242
observer.disconnect();
246243

247-
// it might have not yet handled some mutations
244+
//potrebbe non avere ancora gestito alcune mutations
248245
let mutationRecords = observer.takeRecords();
249246
// process mutationRecords
250247
```
251248

252249
## Garbage collection
253250

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.
255252

256-
## Summary
253+
## Riepilogo
257254

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.
259256

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&igrave; come quando integriamo script di terze parti.
261258

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

Comments
 (0)