callback function meaning
Solution 1:
JavaScript's "callback" is function object that can be passed to some other function (like a function pointer or a delegate function), and then called when the function completes, or when there is a need to do so. For example, you can have one main function to which you can pass a function that it will call...
Main function can look like this:
function mainFunc(callBack)
{
alert("After you click ok, I'll call your callBack");
//Now lets call the CallBack function
callBack();
}
You will call it like this:
mainFunc(function(){alert("LALALALALALA ITS CALLBACK!");}
Or:
function thisIsCallback()
{
alert("LALALALALALA ITS CALLBACK!");
}
mainFunc(thisIsCallback);
This is extensively used in javascript libraries. For example jQuery's animation() function can be passed a function like this to be called when the animation ends.
Passing callback function to some other function doesn't guarantee that it will be called. Executing a callback call (calBack()
) totally depends on that function's implementation.
Even the name "call-back" is self-explanatory... =)
Solution 2:
It's just a name for a function that should be called back after something.
It's often used with XMLHttpRequest:
var x = new XMLHttpRequest();
x.onreadystatechange = function(){
if(x.readyState == 4){
callbackfunction(x.responseText);
}
}
x.open('get', 'http://example.com/', true);
x.send(null);
callbackfunction
is just a plain function, in this case:
function callbackfunction(text){
alert("I received: " + text);
}
Solution 3:
Besides just being a function, a callback function is an enabler for asynchronous application design.
Instead of calling a function and waiting for the return value(s), potentially locking up the thread or the entire PC or UI on single threaded systems while you wait, with the async pattern you call a function, it returns before finishing, and then you can exit your code (return back to the calling OS, idle state, run loop, whatever...). Then later, the OS or asynchronous function calls your code back. The code you want it to call back is usually encapsulated in something called a "callback function". There are other uses, but this is a common one in OOP UI frameworks.
With the latest iOS 4.x, you can also use nameless "blocks" for the callback. But languages that don't have blocks (or anon closures under another name) use functions for function callbacks.