我可以使用什么事件来检测对象中的值更改并获取更改值的键?

What event can I use to a detect a value change in an object AND get the key of the changed value?

我有一个包含一些(简单的)key: value 对的对象,如下所示:

var things = {
  "0": "apple",
  "1": "mango",
  "2": "pear"
  // ect...
};

Object.prototype 中是否有内置函数或方法可用于侦听对象值的变化?

也许是这样的:

things.onchange = function() {
  alert(things[Key_Of_Value_That_Changed]);
};

我不介意使用 jQuery 并且浏览器支持不是一个重要的优先事项,所以 非标准 和/或 自定义方法也欢迎。

您可以使用更通用的 setter 函数,并在适用时使用它(您控制设置值)。

var things = {
  "0": "apple",
  "1": "mango",
  "2": "pear",
  // ect...

  set_val: function (key, val) {
    this[key] = val;
    this.onchange(key);
  },

  onchange: function () {}
};

things.onchange = function(key) {
  alert(key);
};

通常,您可以使用一个函数来设置值并从那里调用它,但如果您必须确保在更改时调用它,您可以使用 Proxy。这允许您在设置 属性 时调用函数。

var trueThings = new Proxy(things, {
  set: // your function here
});

编辑 2016 年 10 月 3 日:

有一种更广泛支持的强制它通过函数的方法,那就是创建一个 shell 对象,该对象将使用 closure 访问主对象。就像 Proxy 一样,它包装对象(保持私有)并提供操作它的工具。您可以使用以下函数来创建它:

function makeShell(obj) {
    function setCallback(k, v, obj) {
        // your callback here
    }

    return {
        get: function(k) {
            return obj[k];
        },
        set: function(k, v) {
            setCallback(k, v);
            obj[k] = v;
        }
    }
}

可以创建一个元素,将元素属性设置为对象属性,使用MutationObserver

var things = {
  "prop-0": "apple",
  "prop-1": "mango",
  "prop-2": "pear"
    // ect...
};

var obj = document.createElement("div");

for (var prop in things) {
  obj.setAttribute(prop, things[prop])
};

var target = obj;

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    things[mutation.attributeName] = obj.getAttribute(mutation.attributeName);
    console.log(obj.getAttribute(mutation.attributeName)
               , things);
  });
});

var config = {
  attributeFilter: Object.keys(things)
};

observer.observe(target, config);

obj.setAttribute("prop-0", "abc");

这是最终产品,它是 Slayther's 的修改版本:

var things = {
  "0": "apple",
  set: function(key, val) {
    var old = (this[key]) ? this[key] : null;
    this["OLD_" + key] = old;
    this[key] = val;
    this.onchange(key, val, old);
  },
  onchange: function(key, value, old) {
    // handle "onchange" business here
  }
};

things.set("0", "pear");

再次感谢 Slayther,对于那些想要看到它的人来说,有一个 demo over on Codepen