I’m building a javascript object which mainly should send an authentication ajax request before processing any other function on it.
Example:
hello={
say:function(txt){
alert(txt);
},
auth:function(){
... ajax ...
}
}
hello.say("hello world!");
The alert should not be triggered until the authentication ajax request is successfully fetched. It’s like queuing any functions to the object until the initialization is done.
P.S. the auth should be automatically fired when the page is fully loaded.
- EDIT
Attempt to use SLaks method:
functionQueue = [];
function exec(func) {
if (functionQueue){
functionQueue.push(func);
}else{
func();
}
}
hello={
say:function(txt){
alert(txt);
},
auth:function(){
ajax.post("http://www.hello.com",function(resp){
var queue = functionQueue;
functionQueue = false; //Prevent re-entrancy
for (var i = 0; i < queue.length; i++){
queue[i]();
}
});
}
}
function start(){
hello.auth();
}
window.addEventListener("load", start, false);
hello.say("hello world!");
Would absolutely appreciate your help.
Thanks!
Make an array of functions to execute, push each function to the array if the request isn’t finished yet, then loop through the array executing functions when the AJAX request finishes.
For example:
EDIT: Demo
2nd EDIT: To use
execinside an object, it can be useful to preservethis:You might want to put the queue inside your object: