Skip to content

Instantly share code, notes, and snippets.

@MrKou47
Created March 7, 2024 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrKou47/3760e426b75dbfa3fa4863910975a30b to your computer and use it in GitHub Desktop.
Save MrKou47/3760e426b75dbfa3fa4863910975a30b to your computer and use it in GitHub Desktop.
Observe Object changes in Javascript
function observe(object, onChange) {
function buildProxy(prefix, object) {
return new Proxy(object, {
set(target, property, value) {
// calling original set property value
target[property] = value;
// log the change
// @ts-ignore
console.log(`Property ${prefix}${property} has changed to: `, value);
onChange(); // Call the callback function
return true;
},
deleteProperty(target, property) {
// deleting the property from the target
delete target[property];
// log the operation
debugger;
// @ts-ignore
console.log(`Property ${prefix}${property} was deleted`);
onChange(); // Call the callback function
return true;
},
get(target, property) {
// property is an index in case of array type
if(typeof target[property] === 'object' && target[property] !== null) {
// @ts-ignore
return buildProxy(`${prefix}${property}.`, target[property]);
} else {
return target[property]; // else returns the actual value
}
},
});
}
return buildProxy("", object);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment