Ways to check in real time if an object has been changed

Asked

Viewed 108 times

1

I was looking for a way to check if an object was altered.

I did it in "gambiarra" mode using setInterval to keep checking all the time if it was changed, but I don’t know if it would be a good way to check.

How can I check if the object has been changed in a simpler or more efficient way?

let obj = {
  item:"valor"
}

function ObjectListener(object, func){
  let savedObject = JSON.stringify(object);
  let listener = setInterval(onChange, 0);
  function onChange(){
    if(savedObject !== JSON.stringify(object)){
      savedObject = JSON.stringify(object)
      func();
      clearInterval(listener);
      listener = setInterval(onChange, 0);
    }
  }
}

new ObjectListener(obj, () => console.log("Alterado"));
<h3>Digite um valor e clique em alterar</h3>
<input id="input">
<button onclick="obj.item = document.getElementById('input').value">Alterar</button>

1 answer

3


You can use a Proxy, that according to the documentation:

is used to define custom behavior for fundamental Operations (e.g. Property lookup, assignment, enumeration, Function Invocation, etc)

That is, it is used to define a custom behavior for some fundamental operations, among them the attribution of a value.

In this case, to assign a value to the object, just define in the method set a custom behavior for when a property is changed:

let obj = {
  item:"valor"
}

obj = new Proxy(obj, {
  set: function (target, chave, valor) {
      console.log(`${chave} alterado para: ${valor}`);
      target[chave] = valor;
      return true;
  }
});
<h3>Digite um valor e clique em alterar</h3>
<input id="input">
<button onclick="obj.item = document.getElementById('input').value">Alterar</button>

According to the documentation, most browsers already support this feature (with the exception of IE).

Browser other questions tagged

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