|
1 | | -The solution consists of two parts: |
| 1 | +La solución consiste de dos 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 | +1. Cuando `.observe(handler)` es llamado, necesitamos recordar el manejador 'handler' en algún lugar para poder llamarlo después. Podemos almacenar los manejadores directamente en el objeto, usando nuestro symbol como clave de la propiedad. |
| 4 | +2. Necesitamos un proxy con la trampa `set` que llame a los manejadores en caso de cualquier cambio. |
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. Inicializa el almacén de manejadores |
11 | 11 | target[handlers] = []; |
12 | 12 |
|
13 | | - // Store the handler function in array for future calls |
| 13 | + // Almacena la función manejadora en el array para llamadas futuras |
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. Crea un proxy para manejar cambios |
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); // reenvía la operación al objeto |
| 22 | + if (success) { // si no hay errores al establecer la propiedad |
| 23 | + // llama a todos los manejadores |
24 | 24 | target[handlers].forEach(handler => handler(property, value)); |
25 | 25 | } |
26 | 26 | return success; |
|
0 commit comments