Object.watch() for all browsers?

前端 未结 8 740
囚心锁ツ
囚心锁ツ 2020-11-22 13:06

Please note that Object.Watch and Object.Observe are both deprecated now (as of Jun 2018).


I was looking for an easy way to monitor an object

8条回答
  •  余生分开走
    2020-11-22 13:36

    The answers to this question are a bit outdated. Object.watch and Object.observe are both deprecated and should not be used.

    Today, you can now use the Proxy object to monitor (and intercept) changes made to an object. Here's a basic example:

    var targetObj = {};
    var targetProxy = new Proxy(targetObj, {
      set: function (target, key, value) {
          console.log(`${key} set to ${value}`);
          target[key] = value;
      }
    });
    
    targetProxy.hello_world = "test"; // console: 'hello_world set to test'
    

    If you need to observe changes made to a nested object, then you need to use a specialized library. I published Observable Slim and it works like this:

    var test = {testing:{}};
    var p = ObservableSlim.create(test, true, function(changes) {
        console.log(JSON.stringify(changes));
    });
    
    p.testing.blah = 42; // console:  [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
    

提交回复
热议问题