Last active
December 18, 2015 16:59
-
-
Save jwerle/5815695 to your computer and use it in GitHub Desktop.
ready function
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) { | |
// 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