Skip to content

Instantly share code, notes, and snippets.

@ccnokes ccnokes/whenready.js
Last active Aug 29, 2015

Embed
What would you like to do?
WhenReady object. Fires callback when all conditions are satisfied.
//executes a callback when all conditions are satisfied
function WhenReady(obj, cb) {
this.conditions = obj;
this.readyCallback = cb;
}
WhenReady.prototype = {
satisfyCondition: function(o) {
if(typeof o == 'object') {
for(var key in this.conditions) {
if(o[key]) {
this.conditions[key] = o[key];
}
}
//see if all conditions are satisfied, fire readyCallback if they are
this.go();
}
},
go: function() {
var alldone = true;
//check if all conditions satisfied
//if one is false, then don't execute
for(var key in this.conditions) {
if(this.conditions[key] === null) {
alldone = false;
break;
}
}
if(alldone) {
//execute the final callback
this.readyCallback();
}
}
};
//example usage
//init object with conditions and callback
var when = new WhenReady({
ajaxCall: null,
timer: null
}, function(){
console.log('DONE');
});
$.ajax({
url: "http://echo.jsontest.com/",
success: function(data){
when.satisfyCondition({ ajaxCall: true });
}
});
setTimeout(function() {
when.satisfyCondition({ timer: true });
}, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.