A few different functions are called when an event happens. For simplicity sake, let's say I have two different analytics tracking requests sent out. They each have a callback function to redirect a visitor after the response is received.
function analytics(event,callback){
// send analytics event;
if (callback) callback();
}
function analytics2(event,callback){
// send analytics2 event;
if (callback) callback();
}
The callback function is usually:
If: tracking response is received from remote server
Then: redirect to URL
$("a").click(function(){
analytics(
'clicked on ' + $(this).attr('id'),
function(){
location.assign($(this).attr('href'));
}
);
analytics2(
'clicked on ' + $(this).attr('id'),
function(){
location.assign($(this).attr('href'));
}
);
});
Question: What's the best way to queue up these callbacks, so I wait for all callback functions to be ready before redirecting? As it's setup now, whenever the first callback runs the visitor is redirected -- without ever knowing if the server recieved the analytics2() function.
I've seen some sites use their own queue system, I just have no idea how this is implemented.
Any suggestions/thoughts?
Should I set analytics2() as the callback for anlaytics()? But then if I end up not running analytics() then analytics2() would never run. Ideally, I'd like to have a more organized approach.
.deferred()and.then()methods. api.jquery.com/jQuery.Deferred