Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active August 29, 2015 14:03
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 ccnokes/3f58d0116245b76e0c74 to your computer and use it in GitHub Desktop.
Save ccnokes/3f58d0116245b76e0c74 to your computer and use it in GitHub Desktop.
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