Doubt using the JavaScript Proxy API

0

I made this code to study the JavaScript Proxy. It works by detecting the object's property change but when I call the property in the console.log it does not appear changed

JS

var f = {nome: "Fulano"}

f = new Proxy (f, {
  set: (target, prop) => {
        if (prop === "nome") {
        alert('Nome alterado')
    }
  }
})

$('#edita').click(() => {
    f.nome = $('input').val()
  console.log(f.nome)
})

HTML

<input type="text">
<button id="edita">EDITAR NOME</button>

After changing the name in the click event of the button the console.log still displays So-and-so

    
asked by anonymous 25.10.2016 / 20:57

1 answer

1

The Proxy object has a high degree of flexibility, it is not just for observing changes made over an object, and for this reason that when you write a behavior like set , get , has , you need to overwrite it in its entirety. This is what was missing on your set , you have not delegated the assignment behavior to target .

var f = {nome: "Fulano"}

f = new Proxy (f, {
  set(target, prop, value) {
    if (prop === "nome") {
      alert('Nome alterado')
    }

    target[prop] = value;
  }
})
    
25.10.2016 / 21:27