Home >Web Front-end >JS Tutorial >How Can I Detect JavaScript Variable Changes?
Original Question:
Is there an event in JavaScript that triggers when the value of a specific variable is modified? Please consider solutions involving jQuery.
Answer:
Using Proxy Objects:
As of 2018, the Proxy object provides an effective mechanism for monitoring and intercepting object property changes. It works by creating a proxy object that wraps the target object.
var targetObj = {}; var targetProxy = new Proxy(targetObj, { set: function (target, key, value) { console.log(`${key} set to ${value}`); target[key] = value; return true; } }); targetProxy.hello_world = "test"; // console: 'hello_world set to test'
Limitations:
Observing Nested Objects:
For observing changes in nested objects, Specialized libraries like Observable Slim offer a more comprehensive solution.
var test = {testing:{}}; var p = ObservableSlim.create(test, true, function(changes) { console.log(JSON.stringify(changes)); }); p.testing.blah = 42; // console: [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
The above is the detailed content of How Can I Detect JavaScript Variable Changes?. For more information, please follow other related articles on the PHP Chinese website!