'Run a function when deep property is set

I have an object like

const obj = { field1: obj1, field2: obj2 }

and now I'd like to run a function when anything in obj was changed:

function objChanged() { ... }

// decorate obj somehow ...

obj.field3 = data; // objChanged should be called (Proxy can see it)
obj.field1.val = data; //objChanged should be called (Proxy can't see it?)

AFAIK there is a MutationObserver which works only for DOM and Proxy which intercepts only own properties, right?

I do not own obj1 so I can not change it. Is there a way to achieve this functionality?



Solution 1:[1]

Following the piece of code will listen to object property you can iterate over object properties to listen all. I am curious, what are you trying to achieve?

const dog = { bark: true };

function Observer(o, property) {
  var _this = this;
  this.observers = [];

  this.Observe = function (notifyCallback) {
    _this.observers.push(notifyCallback);
  };

  Object.defineProperty(o, property, {
    set: function (val) {
      _this.value = val;
      for (var i = 0; i < _this.observers.length; i++) {
        _this.observers[i](val);
      }
    },
    get: function () {
      return _this.value;
    },
  });
}

const observer = new Observer(dog, "bark");

observer.Observe(function (value) {
  l("Barked");
});

dog.bark = true;
dog.bark = true;
dog.bark = true;
dog.bark = true;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Orgil