如何观察对象的变化?

时间:2017-07-18 02:22:09

标签: javascript object watch changeset

使用这个例子:How to watch for array changes?我试图适应观察对象的问题:

(function() {

  if (!("Proxy" in window)) {
    console.warn("Your browser doesn't support Proxies.");
    return;
  }

  var ob = {"a":["a", "b", "c", "d"]};

  // a proxy for our ob
  var proxy = new Proxy(ob, {
    apply: function(target, thisArg, argumentsList) {
      return thisArg[target].apply(this, argumentList);
    },
    deleteProperty: function(target, property) {
      console.log("Deleted %s", property);
      return true;
    },
    set: function(target, property, value, receiver) {      
      target[property] = value;
      console.log("Set %s to %o", property, value);
      return true;
    }
  });
proxy.a.push("z");

  console.log("Current state of array: %o", ob);

})();

但是push不会触发set.log in set。只有我改变了:

var proxy = new Proxy(ob.a, {...
proxy.push("z");

任何人都可以帮助我吗?谢谢

0 个答案:

没有答案