Skip to content

Instantly share code, notes, and snippets.

@jwerle
Forked from pulsedemon/ready.js
Created June 19, 2013 17:33
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 jwerle/5816189 to your computer and use it in GitHub Desktop.
Save jwerle/5816189 to your computer and use it in GitHub Desktop.
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