Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.
Most of the answers to this question are either outdated, ineffective, or require the inclusion of large bloated libraries:
Today, you can now use the Proxy object to monitor (and intercept) changes made to an object. It is purpose built for what the OP is trying to do. Here's a basic example:
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'
The only drawbacks of the Proxy
object are:
Proxy
object is not available in older browsers (such as IE11) and the polyfill cannot fully replicate Proxy
functionality.Date
) -- the Proxy
object is best paired with plain Objects or Arrays.If you need to observe changes made to a nested object, then you need to use a specialized library such as Observable Slim (which I have published) which works like this:
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}}]