JavaScript
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
bench Improve benchmark Dec 19, 2017
.editorconfig Init Dec 11, 2017
.gitattributes Init Dec 11, 2017
.gitignore Init Dec 11, 2017
.npmrc Init Dec 11, 2017
.travis.yml Init Dec 11, 2017
index.js Init Dec 11, 2017
license Init Dec 11, 2017
package.json Improve benchmark Dec 19, 2017
readme.md Add related project (#5) Dec 16, 2017
test.js Init Dec 11, 2017

readme.md

on-change Build Status

Watch an object or array for changes

It works recursively, so it will even detect if you modify a deep property like obj.a.b[0].c = true.

Uses the Proxy API.

Install

$ npm install on-change

Usage

const onChange = require('on-change');

const object = {
	foo: false,
	a: {
		b: [
			{
				c: false
			}
		]
	}
};

let i = 0;
const watchedObject = onChange(object, () => {
	console.log('Object changed:', ++i);
});

watchedObject.foo = true;
//=> 'Object changed: 1'

watchedObject.a.b[0].c = true;
//=> 'Object changed: 2'

API

onChange(object, onChange)

Returns a version of object that is watched. It's the exact same object, just with some Proxy traps.

object

Type: Object

Object to watch for changes.

onChange

Type: Function

Function that gets called anytime the object changes.

Use-case

I had some code that was like:

const foo = {
	a: 0,
	b: 0
};

//

foo.a = 3;
save(foo);

//

foo.b = 7;
save(foo);


//

foo.a = 10;
save(foo);

Now it can be simplified to:

const foo = onChange({
	a: 0,
	b: 0
}, () => save(foo));

//

foo.a = 3;

//

foo.b = 7;

//

foo.a = 10;

Related

  • known - Allow only access to known object properties (Uses Proxy too)
  • negative-array - Negative array index support array[-1] (Uses Proxy too)
  • statux - State manager (Uses Proxy too)

License

MIT © Sindre Sorhus