Created
March 7, 2024 02:06
-
-
Save MrKou47/3760e426b75dbfa3fa4863910975a30b to your computer and use it in GitHub Desktop.
Observe Object changes in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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