After studying the Dojo addOnLoad functions, I decided to incorporate them into my class. To me, this approach seemed to be the most effective and straightforward. While considering using a pub/sub or dojo.connect method, I believe that this implementation stands out as the cleanest and most intuitive solution.
Here are the key components that I extracted from dojo.js and integrated into my class:
_addToQueue : function(array, object, functionToAdd){
if(!functionToAdd){
array.push(object);
}else if(functionToAdd){
var callback = (typeof functionToAdd == "string") ? object[functionToAdd] : functionToAdd;
array.push(function(){ callback.call(object); });
}
},
_loadComplete : function() {
this._notifyLoading = true;
this._afterLoad = true;
var loadersList = this._loaders;
for(var i = 0; i < loadersList.length; i++){
try{
loadersList[i]();
}catch(error){
throw error;
console.error("addOnLoad callback failed: " + error, error); /* continue with other load events, like the parser, but report the error */
}
}
this._notifyLoading = false;
//Ensure that no additional callbacks were added to the onload queue
//after the initial run. If any were added and there are no more waiting resources,
//rerun the function.
if(this._afterLoad && this._pendingResources == 0 && loadersList.length){
this._loadComplete();
}
},
addOnLoad : function(/*Object?*/object, /*String|Function?*/functionName){
this._addToQueue(this._loaders, object, functionName);
if(this._afterLoad && !this._notifyLoading){
this._loadComplete();
}
}