The perfect, event-driven thing for keeping track of objects, on top of Proxy API
Install keep-track via npm (or yarn if you prefer):
npm install keep-track # or `yarn add keep-track`
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.
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
}
}
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
}