Created
September 11, 2014 22:02
-
-
Save bjoerge/facf9f167baf1cf47ae8 to your computer and use it in GitHub Desktop.
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
var EventEmitter = require("events").EventEmitter; | |
// A thing to manage/track state changes | |
// Changes passed to setState are queued up and effectuated in the next event loop tick | |
class Stateful extends EventEmitter { | |
constructor() { | |
this.state = this.getInitialState(); | |
this._stateChangeQueue = []; | |
this._stateChangeInProgress = false; | |
} | |
getInitialState() { | |
return {}; | |
} | |
getState() { | |
return this.state; | |
} | |
setState(change) { | |
this._stateChangeQueue.push(change); | |
if (!this._stateChangeInProgress) { | |
setTimeout(this._flushQueue.bind(this), 0); | |
} | |
this._stateChangeInProgress = true; | |
} | |
_flushQueue() { | |
var mergedChange = this._stateChangeQueue.reduce((result, change)=> Object.assign(change, result), {}); | |
this.state = Object.assign(this.state, mergedChange); | |
this._stateChangeQueue = []; | |
this.emit('change'); | |
} | |
} | |
module.exports = Stateful; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment