Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

on-change

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

on-change

Watch an object or array for changes

  • 0.2.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
77K
increased by6.63%
Maintainers
1
Weekly downloads
 
Created
Source

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;
  • 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)
  • introspected - Never-ending Proxy with multiple observers (Uses Proxy too)

License

MIT © Sindre Sorhus

Keywords

FAQs

Package last updated on 15 Dec 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc