Skip to content

Instantly share code, notes, and snippets.

@jwerle
Last active December 18, 2015 16:59
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/5815695 to your computer and use it in GitHub Desktop.
Save jwerle/5815695 to your computer and use it in GitHub Desktop.
ready function
var app = {}
!function (app) {
// boolean to indicate whether
// the `app` is ready
var isReady = false;
// the ready stack to house
// all of the callbacks pushed
// to it
var readyStack = [];
app.ready = function (fn) {
// 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) {
// wait for next tick in event loop
// to keep things asynchronous
setTimeout(fn.bind(app), 0);
} else {
readyStack.push(fn.bind(app));
}
// chaining is classy
return this;
};
app.emitReady = function () {
var fn, i, len = readyStack.length
// set internal `isReady` boolean
// to true so the `app` knows
// it is ready
isReady = true;
// iterate and call each callback
// in the `readyStack`
for (i = 0; i < len; ++i) {
fn = readyStack[i];
// execute the callback
fn();
}
}
}(app);
// maybe some jquery coolness
$(app.emitReady);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment