I would like to observe whenever a property of a third party object is changed. I'm taking the approach of assigning a custom setter but my console.log
below is never invoked. Why is that? Is there a better approach?
const foo = { a: 1, b: 2 };
Object.assign(foo, {
set user(user) {
foo.user = user;
console.log(">>>>>> user was changed", user);
},
});
foo.user = "asdf";
Please note, I need to mutate foo
I cannot wrap a proxy around foo and return that because it is a third party library which sets .user
internally
CodePudding user response:
I've found a way, pretty hacky as it is
const foo = { a: 1, b: 2 };
let underlyingValue = foo.user
Object.defineProperty(foo, "user", {
get() {
return underlyingValue
},
set(user) {
underlyingValue = user;
console.log(">>>>>> user was changed", user);
},
enumerable: true,
configurable: false
});
foo.user = "asdf";
console.log(foo)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I've made this into a generic function below