Watch an object for changes in Vanilla JavaScript

const obj = {   foo: “bar”};function repeatChecking(oldValue) {  if(oldValue) {    setInterval(() => {     if(obj.foo !== oldValue) {      console.log(`Value of ${oldValue} to ${obj.foo}`);      oldValue = obj.foo;      }    }, 10);  }}repeatChecking(obj.foo);obj.foo = “I have changed.”;setTimeout(()=> {  obj.foo = “I have changed again.”;}, 1000);
obj.watch(“foo”, function (oldValue, newValue) {console.log(`Value of foo changed from ${oldValue} to ${newValue}`);});
obj.watch(“foo”, function (oldValue, newValue) {console.log(`Value of foo changed from ${oldValue} to ${newValue}`);});obj.foo = “I have changed.”;obj.foo = “I have changed again.”;delete obj.foo;obj.foo = “I am back from dead!”;obj.unwatch(‘foo’);obj.foo = “Finally, I am no one.”
var obj = {
foo: "Initial Value"
};

Object.observe(obj, function(changes) {
console.log(changes);
});
obj.newProp = "I am new Property";
// [{name: 'newProp', object: <obj>, type: 'add'}]
obj.foo = 'New Value of Foo';
// [{name: 'foo', object: <obj>, type: 'update', oldValue: 'Initial Value'}]
delete obj.newProp;
// [{name: 'newProp', object: <obj>, type: 'delete', oldValue: 'I am new Property'}]
const obj = {  fooValue: “bar”,  get foo() {    return this.fooValue;  },  set foo(val) {    this.fooValue = val;    this.fooListener(val);  },  fooListener: function (val) {},  registerNewListener: function (externalListenerFunction) {    this.fooListener = externalListenerFunction;  },};obj.registerNewListener((val) => console.log(`New Value: ${val}`));
obj.foo = “I have changed.”;obj.foo = “I have changed again.”;delete obj.foo;obj.foo = “I am back from dead!”;
New Value: I have changed.
New Value: I have changed again.
const obj = {  foo: “bar”,};const objProxy = new Proxy(obj, {  set: function (target, key, value) {   console.log(`${key} set from ${obj.foo} to ${value}`);   target[key] = value;   return true; },});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store