I can do this to check if a global variable is defined or not:
if (window.globalVariableName) {
// it's defined, now it's safe to work with it
}
Now I have a nested hierarchy, that I should work on only if every nested object is defined up to the leaf, and this nested hierarchy can be anything. For example I can have these two hierarchies:
human.head.mouth.lips.upperLip.color
building.firstFloor.hallway.lastRoom.chair.density
I want to check for existence of all the nesting, up to the leaf value, and only if the entire hierarchy including the leaf are defined, then do something. In other words I want to be able to dynamically create this static code:
if (window.human.head.mouth.lips.upperLip.color) {
// now I know human is defined, and head, and mouth, and ... and up to color
}
I tried this code, but it's not working:
function checkThenRun(targetToWaitFor, callback) {
if (typeof callback !== "function") {
console.error('Callback for checkThenRun should be a function');
return;
}
if (targetToWaitFor.indexOf('.') > -1) {
targetToWaitFor.split('.').reduce(function (anchor, recursion) {
if (anchor) {
globalVariableForReducingInWaitAndRun = window[anchor];
if (globalVariableForReducingInWaitAndRun) {
globalVariableForReducingInWaitAndRun = globalVariableForReducingInWaitAndRun[recursion];
}
}
else {
globalVariableForReducingInWaitAndRun = globalVariableForReducingInWaitAndRun[recursion];
}
});
if (!globalVariableForReducingInWaitAndRun) {
console.warn('checkThenRun waiting for ' + targetToWaitFor + '...');
setTimeout(function () {
checkThenRun(targetToWaitFor, callback);
}, 500);
return;
}
}
if (typeof window[targetToWaitFor] === "undefined") {
console.warn('checkThenRun waiting for ' + targetToWaitFor + '...');
setTimeout(function () {
checkThenRun(targetToWaitFor, callback);
}, 50)
return;
}
callback();
}
This is the usage sample:
checkAndRun('human.head.mouth.lips.upperLip.color', function() {
// now I know this hierarchy is created, I can change color for example
});
Update:
I'm developing a system based on a mashup architecture. A web page is populated from many different sources. I can't and I don't have access to those external sources. I can't ask them to provide an API for me because they don't exist. It's another system that works, and injects something into the page but through asynchronous operation, thus I don't know when that operation is finished. But I can start my operation only after that. This is why I need to check the existence of the entire hierarchy.