|
1 | | -The solution consists of two parts: |
| 1 | +A solução consiste em duas partes: |
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 | + |
| 4 | +1. Sempre que `.observe(handler)` for chamado, precisamos lembrar do manipulador em algum lugar, para ser capaz de chamá-lo depois. Podemos armazenar os manipuladores no próprio objeto, usando nosso symbol como chave da propriedade. |
| 5 | +2. Precisamos de um proxy com um `set` para chamar todos os manipuladores caso de aconteça qualquer alteração. |
5 | 6 |
|
6 | 7 | ```js run |
7 | 8 | let handlers = Symbol('handlers'); |
8 | 9 |
|
9 | 10 | function makeObservable(target) { |
10 | | - // 1. Initialize handlers store |
| 11 | + // 1. inicializa o armazenamento de manipuladores |
11 | 12 | target[handlers] = []; |
12 | 13 |
|
13 | | - // Store the handler function in array for future calls |
| 14 | + // Armazena a função manipuladora no array para futuras chamadas |
14 | 15 | target.observe = function(handler) { |
15 | 16 | this[handlers].push(handler); |
16 | 17 | }; |
17 | 18 |
|
18 | | - // 2. Create a proxy to handle changes |
| 19 | + // 2. Cria um proxy para lidar com as mudanças |
19 | 20 | return new Proxy(target, { |
20 | 21 | 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 |
| 22 | + let success = Reflect.set(...arguments); // Encaminha a operação para o objeto |
| 23 | + if (success) { // Se não houver erro ao definir a propriedade |
| 24 | + // chama rodos os manipuladores |
24 | 25 | target[handlers].forEach(handler => handler(property, value)); |
25 | 26 | } |
26 | 27 | return success; |
|
0 commit comments