-
-
Save jwerle/5816189 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 app = {} | |
!function (app) { | |
// container to push booleans | |
// for each event to indicate whether | |
// the `app` is ready | |
var isReady = []; | |
// the ready stack to house | |
// all of the callbacks pushed | |
// to it | |
var readyStack = []; | |
app.ready = function (e, fn) { | |
// ensure `event` is a string | |
if ('string' !== typeof e) throw new TypeError("expecting string"); | |
// ensure `fn` is a function | |
if ('function' !== typeof fn) throw new TypeError("expecting function"); | |
// `app` is already ready so | |
// we can just call the `fn` | |
// function | |
if (isReady[isReady.indexOf(e)]) { | |
// wait for next tick in event loop | |
// to keep things asynchronous | |
setTimeout(fn.bind(app), 0); | |
} else { | |
if ('array' !== typeof readyStack[e]) readyStack[e] = []; | |
readyStack[e].push(fn.bind(app)); | |
} | |
// chaining is classy | |
return this; | |
}; | |
app.emitReady = function (e) { | |
if (!readyStack[e]) throw new TypeError("ready event '" + e + "' is undefined"); | |
var fn, i, len = readyStack[e].length | |
// set internal `isReady` boolean | |
// to true so the `app` knows | |
// it is ready | |
isReady[e] = true; | |
// iterate and call each callback | |
// in the `readyStack` | |
for (i = 0; i < len; ++i) { | |
fn = readyStack[e][i]; | |
// execute the callback | |
fn(); | |
} | |
} | |
}(app); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment