Created
August 19, 2014 03:37
-
-
Save staydecent/4ed155ed0313e24510d9 to your computer and use it in GitHub Desktop.
Dispatcher / Synchronous 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
/** | |
* 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