|
1 | | -The solution consists of two parts: |
| 1 | +La soluzione consiste di due parti: |
2 | 2 |
|
3 | | -1. Whenever `.observe(handler)` is called, we need to remember the handler somewhere, to be able to call it later. We can store handlers right in the object, using our symbol as the property key. |
4 | | -2. We need a proxy with `set` trap to call handlers in case of any change. |
| 3 | +1. Quando `.observe(handler)` viene invocato, dobbiamo memorizzare l'handler da qualche parte, per poter essere in grado di invocarlo più tardi. Possiamo memorizzare gli handler nell'oggetto, utilizzando un symbol come chiave della proprietà. |
| 4 | +2. Abbiamo bisogno di un proxy con la trappola `set` per poter invocare gli handlers in caso di cambiamenti. |
5 | 5 |
|
6 | 6 | ```js run |
7 | 7 | let handlers = Symbol('handlers'); |
8 | 8 |
|
9 | 9 | function makeObservable(target) { |
10 | | - // 1. Initialize handlers store |
| 10 | + // 1. Inizializziamo lo store per gli handlers |
11 | 11 | target[handlers] = []; |
12 | 12 |
|
13 | | - // Store the handler function in array for future calls |
| 13 | + // Memorizziamo l'handler nell'array per poterlo invocare successivamente |
14 | 14 | target.observe = function(handler) { |
15 | 15 | this[handlers].push(handler); |
16 | 16 | }; |
17 | 17 |
|
18 | | - // 2. Create a proxy to handle changes |
| 18 | + // 2. Creiamo un proxy per gestire le modifiche |
19 | 19 | return new Proxy(target, { |
20 | 20 | set(target, property, value, receiver) { |
21 | | - let success = Reflect.set(...arguments); // forward the operation to object |
22 | | - if (success) { // if there were no error while setting the property |
23 | | - // call all handlers |
| 21 | + let success = Reflect.set(...arguments); // inoltriamo l'operazione all'oggetto |
| 22 | + if (success) { // se non è stato generato alcun errore durante il cambiamento della proprietà |
| 23 | + // invochiamo tutti gli handlers |
24 | 24 | target[handlers].forEach(handler => handler(property, value)); |
25 | 25 | } |
26 | 26 | return success; |
|
0 commit comments