Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


2 Answers

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);
};
like image 193
Božo Stojković Avatar answered Sep 21 '25 21:09

Božo Stojković


You can create an element, set element attributes to object properties, use 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");
like image 30
guest271314 Avatar answered Sep 21 '25 20:09

guest271314