Skip to content

Instantly share code, notes, and snippets.

@staydecent
Created August 19, 2014 03:37
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 staydecent/4ed155ed0313e24510d9 to your computer and use it in GitHub Desktop.
Save staydecent/4ed155ed0313e24510d9 to your computer and use it in GitHub Desktop.
Dispatcher / Synchronous Events
/**
* Dispatcher
*
* Requires: <script src="http://d3js.org/queue.v1.min.js"></script>
*/
var Dispatcher = function() {
this._q = queue(1);
this._events = {};
this._E = function(message) {
this.message = message;
this.name = "DispatcherException";
this.toString = function() {
return this.name + ': ' + this.message;
};
};
};
Dispatcher.prototype = {
on: function(event, fn) {
this._events[event] = this._events[event] || [];
this._events[event].push(fn);
},
off: function(event, fn) {
if (event in this._events === false) { return; }
this._events[event].splice(this._events[event].indexOf(fn), 1);
},
trigger: function(event /* , args... */) {
if (event in this._events === false) { return; }
var ctx = this;
var args = Array.prototype.slice.call(arguments, 1);
var tasks = [];
// create an array of tasks out of our event fns for queue
this._events[event].forEach(function(fn) {
tasks.push(function(cb) {
var promise = fn.apply(ctx, args);
if (promise === undefined) {
throw new ctx._E('Callback must return a value or a Promise.');
}
if (typeof promise.then === 'function') {
promise.then(
function(value) { cb(null, value); },
function(value) { cb(value); });
} else {
cb(null, promise);
}
});
});
tasks.forEach(function(t) { ctx._q.defer(t); });
this._q.awaitAll(function(error, results) { console.log("all done!"); });
}
};
// Example usage:
//
// var appDispatcher = new Dispatcher();
//
// appDispatcher.on('change.currentPage', function(name) {
// appState.currentPage = name;
// render();
// return true;
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment