Home > Software engineering >  How to observe property value changes of a third party object?
How to observe property value changes of a third party object?

Time:12-01

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);
  },
});

// Desired behaviour
foo.user = "asdf"; // >>>>>> user was changed asdf
delete foo.user; // >>>>>> user was changed undefined
foo.user = "asdf1" // >>>>>> user was changed asdf1

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 mutates .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
});

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

  • Related