SilverSurfer
SilverSurfer

Reputation: 4365

How to detect when object value change?

I'm trying to listen when a object value changes using a Javascript proxy object in a easy and readable way. I followed this Stack Overflow question and Mozilla docs. But I cannot understand how to do it to achieve my goal.

var values ={Value1: 0, Value2:0};
var checkObjectChange = new Proxy(values, {});

console.log("The object values are: "+JSON.stringify(values))

$("#btn1").on("click", function() {
    values.Value1 = 1;
    console.log("Now the object values are: "+JSON.stringify(values));
});

$("#btn2").on("click", function() {
    values.Value2 = 1;
    console.log("Now the object values are: "+JSON.stringify(values));
});

//Im expecting to call a function when a object value changes
function whenChange() {
  console.log("The value of the object has changed!");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="btn1">Change value 1</button>
<button id="btn2">Change value 2</button>

Upvotes: 1

Views: 3087

Answers (1)

Code Maniac
Code Maniac

Reputation: 37775

You can pass the handler function to Proxy and you need to change values on proxies not on original object

var values ={Value1: 0, Value2:0};

let handler = {
  set: function whenChange(obj,prop,value) {
    obj[prop] = value
  console.log("The value of the object has changed!");
  return true
 }
}
var checkObjectChange = new Proxy(values, handler);

console.log("The object values are: "+JSON.stringify(checkObjectChange))

$("#btn1").on("click", function() {
    checkObjectChange.Value1 = 1;
    console.log("Now the object values are: "+JSON.stringify(checkObjectChange));
});

$("#btn2").on("click", function() {
    checkObjectChange.Value2 = 1;
    console.log("Now the object values are: "+JSON.stringify(checkObjectChange));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="btn1">Change value 1</button>
<button id="btn2">Change value 2</button>

Upvotes: 1

Related Questions