Last active
August 29, 2015 14:03
-
-
Save ccnokes/3f58d0116245b76e0c74 to your computer and use it in GitHub Desktop.
WhenReady object. Fires callback when all conditions are satisfied.
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
//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