Skip to content

The perfect, event-driven thing for keeping track of objects, on top of Proxy API

License

Notifications You must be signed in to change notification settings

heokhe/keep-track

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

keep-track

The perfect, event-driven thing for keeping track of objects, on top of Proxy API

Installation

Install keep-track via npm (or yarn if you prefer):

npm install keep-track # or `yarn add keep-track`

Usage

Take a look at following code:

const keepTrack = require('keep-track')
let target = {
	a: 1,
	b: 5,
	d: 12,
	r: null
}

let proxified = keepTrack(target, {
	// here come event handlers
	willSet(newValue, oldValue, keyName){
		console.log(`the key ${keyName} has changed from ${oldValue} to ${newValue}`)
	},
	didSet(){
		console.log('changed!')
	}
})

now we have the proxified object that is reactive. before a key change, the willSet event handler will be executed; after the change, the didSet handler will be executed with exactly same arguments.

Validation

willSet handler function can return something. if the returned value is truthy (or undefined), change will be aborted.

willSet(n, o, k){
	if (k === 'age' && n > 110){
		console.log('age cannot be more than 110')
		return false
	}
}

Async validations

for async operations, you can use Promises:

willSet(n, o, k){
	someAsyncValidation(n).then(result => result.ok)
}

Or, do it in async/await way:

async willSet(n, o, k){
	const {ok} = await someAsyncValidation(n)
	return ok
}

About

The perfect, event-driven thing for keeping track of objects, on top of Proxy API

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published