I found this gist to detect changes on specified fiels of a object : https://gist.github.com/3138469
But it bind an event only on one field.
Someone know a function or a tricks to detect change on an entire Javascript Object ?
I found this gist to detect changes on specified fiels of a object : https://gist.github.com/3138469
But it bind an event only on one field.
Someone know a function or a tricks to detect change on an entire Javascript Object ?
2019 Update: These days this can be achieved using Proxy API in a much more efficient manner. The on-change library uses the Proxy API behind the scene to make this even easier.
2012 Update: I've just noticed that the author of Watch.js is referencing a library with much broader browsers' support. MultiGetSet.JS
When I want to achieve this I usually use Watch.js, you can watch a whole object or one attribute.
This is currently not possible, you can only define getters/setters for individual properties.
Yet, there is a draft for Proxy objects which could do that. Today, it is only supported in Firefox' Javascript 1.8.5.
Example using JavaScript's Proxy API.
You can reflect to changes made to some i.e: data object:
const react = (obj, cb) => new Proxy(obj, {
set(t, key, val, r) {
const old = t[key];
const ref = Reflect.set(t, key, val, r);
cb(key, val, old);
return ref;
}
});
// Data from server:
const data = { name: "John", age: 29 };
// Make user a Proxy of data, and react to changes with a callback:
const user = react(data, (key, val, old) => {
console.log(`User changed ${key} value from: ${old} to: ${val}`);
});
// Change values on the Proxy!
user.name = "Johnatan";
user.age += 1;
// Let's test the original data
console.log("Original data is also updated:", { data });
Tip:
if you want to react immediately i.e: you want to update the DOM on page load (and also dynamically on a value change) wrap the Proxy inside Object.assign() (in order to trigger the setter):
const react = (obj, cb) => Object.assign(new Proxy(obj, {
set(target, key, val) {
const old = target[key];
const ref = Reflect.set(...arguments);
cb(key, val, old);
return ref;
}
}), obj);
const el = (sel, par = document) => par.querySelector(sel);
const data = { name: "John", age: 29 };
const user = react(data, (key, val) => {
el(`[data-react="${key}"]`).textContent = val;
});
// Change values on the Proxy (Not on Data) in order to react:
setTimeout(() => user.name = "Johnatan", 1000);
setTimeout(() => user.age += 1, 2000);
Name: <span data-react="name"></span>
Age: <span data-react="age"></span>