Skip to content

Instantly share code, notes, and snippets.

@pulsedemon
Last active December 18, 2015 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pulsedemon/5816061 to your computer and use it in GitHub Desktop.
Save pulsedemon/5816061 to your computer and use it in GitHub Desktop.
Modified version of a ready function @jwerle wrote
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);
@pulsedemon
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment