|
1 | | -The solution consists of two parts: |
| 1 | +La solution se compose de deux parties: |
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. Chaque fois que `.observe(handler)` est appelé, nous devons nous souvenir du handler quelque part, pour pouvoir l'appeler plus tard. Nous pouvons stocker des handler directement dans l'objet, en utilisant notre symbole comme clé de propriété |
| 4 | +2. Nous avons besoin d'un proxy avec le piège `set` pour appeler les handler en cas de changement |
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. initialiser le stockage de l'handler |
11 | 11 | target[handlers] = []; |
12 | 12 |
|
13 | | - // Store the handler function in array for future calls |
| 13 | + // Stocker la fonction de l'handler dans un tableau pour les appels futurs |
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. Créer un proxy pour gérer les modifications |
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); // transmettre l'opération à l'objet |
| 22 | + if (success) { // s'il n'y a pas eu d'erreur lors de la définition de la propriété |
| 23 | + // appeler tous les handler |
24 | 24 | target[handlers].forEach(handler => handler(property, value)); |
25 | 25 | } |
26 | 26 | return success; |
|
0 commit comments