Created
March 2, 2021 15:16
-
-
Save dotandimet/e1cf7903390bf0fa0e9ee1bf3d812748 to your computer and use it in GitHub Desktop.
An Observable object that emits change events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const EventEmitter = require('events'); | |
class Observable extends EventEmitter { | |
constructor(source) { | |
super(); | |
this.self = {}; | |
for (let prop in source) { | |
if (prop === 'self') | |
continue; | |
this.self[prop] = source[prop]; | |
Object.defineProperty(this, prop,. | |
{ set: function(value) { | |
this.emit('change', { 'property': prop, 'old': this.self[prop], 'new': value }); | |
this.self[prop] = value; | |
}, get: function() { | |
return this.self[prop]; | |
} | |
}); | |
} | |
} | |
} | |
const bob = new Observable({ color: 'red', counter: 0, friends: [] }); | |
bob.on('change', (ev) => { | |
console.log(`property ${ev.property} changed from ${ev.old} to ${ev.new}`); | |
}); | |
const incr = setInterval( () => { bob.counter++; if (bob.counter > 10) { clearInterval(incr) } }, 150 ); | |
setTimeout( () => { bob.color = 'blue' }, 100 ); | |
setTimeout( () => { bob.color = 'green' }, 200 ); | |
setTimeout( () => { bob.friends = [ ...bob.friends, 'Jerry' ] }, 100 ); | |
setTimeout( () => { bob.friends = [ ...bob.friends, 'Donald' ] }, 100 ); | |
setTimeout( () => { bob.friends = [ 'Todd', ...bob.friends ] }, 100 ); | |
setTimeout( () => { bob.friends = [] }, 100 ); | |
setTimeout( () => { bob.color = 'red' }, 100 ); | |
setTimeout( () => { bob.color = 'blue' }, 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment