Observing changes to the property of an object has always been a much sought after task. Many holds have been used over the years to listen to changes in objects. Nowadays, we have better methods to listen to the changes of objects: the Proxy API. Sindre Sorhus created on-change a small JavaScript tool that lets you listen to changes on JavaScript objects and tables!

JavaScript is being modified

As the code of change is so small, here it is in all its splendor:

& # 39; use strict & # 39 ;;

module.exports = (object, onChange) => {
const manager = {
get (target, property, recipient) {
try {
returns a new proxy (target [property] manager);
} catch (err) {
return Reflect.get (target, property, receiver);
defineProperty (target, property, descriptor) {
about change ();
return Reflect.defineProperty (target, property, descriptor);
deleteProperty (target, property) {
about change ();
return Reflect.deleteProperty (target, property);

return new Proxy (object, manager);

The onChange function returns a proxy that you will use to modify objects.

Using Change

Pass onChange the item you want to spy on and a change manager function:

let j = {
a: 1

// When editing, save to the server
let modifiable = onChange (j, () => save (j));

Then use this proxy to modify properties and be notified of changes:

// Make a change that would trigger changes
changeable.a = 2;

// save () is triggered!

// j.a === 2

Note that the values ​​of the original object also change – that is the beauty of Proxy! Also note that the on-change option does not tell you which property has been changed; the use case, as described by Sindre, is to save an object (to a server, etc.) when a part of an object changes. You can also use ti for a small library with a rendering function, making the content every time a property has changed!

This library is very convenient if you do not need to know which property has changed, but that something has changed.


Please enter your comment!
Please enter your name here