A callback is the fancy name for a function which is executed after some other long-running code. An example would be an AJAX request or an animation.
Because the animation or AJAX request might take between 0.1 and 30 seconds to complete, we can't simply set a timeout for the function and hope the request returns prior to the timeout.
To get around this we use callbacks. Heres a quick example:
$.get( url, callback )
Once the GET request returns, callback() will be executed with the result of the GET request as the first variable.But what if you want to do multiple callbacks?
Heres how to do multiple callbacks:
function retrieveData( url )
{
var parentArguments = arguments;
$.get( url, function( data )
{
for( var i = 1; i < parentArguments.length; i++ )
{
callback = parentArguments.i
callback( data )
}
})
}
And to actually the call the function:retrieveData( 'someurl.php', doThis, doThat )
So now you know! Its pretty simple but for beginner JS'ers its not entirely obvious.Now all I need to do is figure out a way to return the data rather than trigger callbacks... SJAX here I come!
No comments:
Post a Comment