Mango Mango - 4 months ago 8
Javascript Question

What event can I use to a detect a Value change in an Object AND get the Key of the changed Value?

I have a Object that contains some (simple)

key: value
pairs like this:

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


Is there a built in function or method in
Object.prototype
that I can use to listen for a change in the values of the Object?

Maybe something like this:

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


I don't mind using jQuery and browser support isn't a big priority so non-standard and / or custom methods are also welcome.

Answer

You could use a more general setter function, and use that, if applicable (You control setting values).

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