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>