如何检测对象值何时更改?

How to detect when object value change?

我正在尝试以一种简单易读的方式使用 Javascript proxy object 来监听对象值的变化。我关注了this Stack Overflow question and Mozilla docs。但我无法理解如何实现我的目标。

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>

您可以将处理函数传递给 Proxy,您需要更改代理而不是原始对象的值

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>