Skip to content

Instantly share code, notes, and snippets.

@EdwardDrapkin
Created September 24, 2015 20:24
Show Gist options
  • Save EdwardDrapkin/07f6c825e56c6bd9b082 to your computer and use it in GitHub Desktop.
Save EdwardDrapkin/07f6c825e56c6bd9b082 to your computer and use it in GitHub Desktop.
import EventEmitter from 'events';
class Dispatcher {
constructor(actions) {
this.subscribers = {};
this.subscriptionId = 0;
this.idPrefix = '____dispatch____';
this.actions = actions;
this.queue = [];
this.isBusy = false;
for(var action in this.actions) {
this.subscribers[action] = {};
}
}
dispatch(action, payload) {
this._verify(action);
if(this.isBusy) {
throw "Can't dispatch while dispatching, use enqueue instead.";
}
this._dispatch(action, payload);
if(this.queue.length > 0) {
var oldQueue = this.queue;
this.queue = [];
for(var i = 0; i < this.queue.length; i++) {
var action = queue[i].action;
var payload = queue[i].payload;
this._dispatch(action, payload);
oldQueue = oldQueue.concat(this.queue);
this.queue = [];
}
}
}
_dispatch(action, payload) {
this.isBusy = true;
for(var id in this.subscribers[action]) {
this.subscribers[action][id](payload);
}
this.isBusy = false;
}
enqueue(action, payload) {
this._verify(action);
if(this.isBusy) {
this.queue.push({action, payload});
} else {
this.dispatch(action, payload);
}
}
subscribe(action, listener, id = this.idPrefix + this.subscriptionId++) {
this._verify(action);
this.subscribers[action][id] = listener;
return id;
}
unsubscribe(action, id) {
this._verify(action);
delete this.subscribers[action][id];
}
_verify(action) {
if(!this.actions[action]) {
throw "No such action: " + action;
}
}
}
export default Dispatcher;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment