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.
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);
};
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With