Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Created September 11, 2014 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerge/facf9f167baf1cf47ae8 to your computer and use it in GitHub Desktop.
Save bjoerge/facf9f167baf1cf47ae8 to your computer and use it in GitHub Desktop.
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