Doubt using the Javascript Proxy API

Asked

Viewed 114 times

1

I made this code to study Javascript Proxy. It works by detecting the change of the object’s property but when I call the property on 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 event, the console.log still displays Fulano

1 answer

2


The object Proxy has a high degree of flexibility, not only serves to observe changes made on top of an object, and precisely for this reason that when you write a behavior like set, get, has, you need to write it all over. That’s what was missing in your set, failed to delegate the attribution behaviour to the target.

var f = {nome: "Fulano"}

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

    target[prop] = value;
  }
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.