callback

Eine Callback-Funktion wird einer anderen Funktion als Paramater übergeben. Diese wird dann mit entsprechenden Paramtern aufgerufen. Wiki: Eine Rückruffunktion (englisch callback function) bezeichnet in der Informatik eine Funktion, die einer anderen Funktion als Parameter übergeben und von dieser unter gewissen Bedingungen aufgerufen wird. Dieses Vorgehen folgt dem Entwurfsmuster der Inversion of Control.

Zum Beispiel preg_replace_callback, sucht nach einem Suchmuster, und ruft, dann die als Paramter angegebene Funktion auf. Diesem Funktionsaufruf werden als Paramter die Treffer übergeben. Die Callback-Funktion kann dann damit weiterarbeiten und liefert letztendlich einen Wert zurück, der durch die Suche ersetzt wird...

<script type="text/javascript">

function someAction(x, y, someCallback) {
    return someCallback(x, y);
}

function calcProduct(x, y) {
    return x * y;
}

function calcSum(x, y) {
    return x + y;
}
// alerts 75, the product of 5 and 15
alert(someAction(5, 15, calcProduct));
// alerts 20, the sum of 5 and 15
alert(someAction(5, 15, calcSum));
</script>


First a function someAction is defined with a parameter intended (bestimmt) for callback: someCallback.
Then a function that can be used as a callback to someAction is defined, calcProduct.
Other functions may be used for someCallback, like calcSum.
In this example, someAction() is invoked twice, once with calcProduct as a callback and once with calcSum.
The functions return the product and sum, respectively, and then the alert will display them to the screen.

In this primitive example, the use of a callback is primarily a demonstration of principle.
One could simply call the callbacks as regular functions, calcProduct(x, y).
Callbacks are generally useful when the function needs to perform actions before the callback is executed,
or when the function does not (or cannot) have meaningful return values to act on, as is the case for Asynchronous
JavaScript (based on timers) or XMLHttpRequest requests.

Useful examples can be found in JavaScript libraries such as jQuery. Each method iterates over an array, the first argument is a callback which is performed on each iteration.


Another trick when calling function asynchronously is to pass in a callback function so your code can be notified when the function call is finished executing. Quelle:http://pietschsoft.com/post/2008/02/JavaScript-Function-Tips-and-Tricks.aspx

var asyncArguments = null;
var asyncCallback = null;

function AddNumbers(a, b, callback)
{
// Save a reference to the arguments
asyncArguments = arguments;

// Save a reference to the callback function
asyncCallback = callback;

// Call Function Asynchronously
window.setTimeout("AsynchronousAddNumbers();", 1);
}

function AsynchronousAddNumbers()
{
// This is call asynchonously by AddNumbers, and then
// calls the callback function when completed and passes
// it the results.
asyncCallback(asyncArguments[0] + asyncArguments[1]);
}

function AddNumbersCallback(result)
{
// This gets called when AddNumbers is completed asynchronously
alert(result);
}


/// Call AddNumbers to do our addition asynchronously
/// and pass it the callback function to call when done
AddNumbers(5, 10, AddNumbersCallback);



How to Write a Callback Function

If you’re writing your own functions or methods, then you might come across a need for a callback function. Here’s a very simple example of a custom callback function:

01.function mySandwich(param1, param2, callback) {
02. alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
03. callback();
04.}
05.
06.mySandwich('ham', 'cheese', function() {
07. alert('Finished eating my sandwich.');
08.});

Here we have a function called mySandwich and it accepts three parameters. The third parameter is the callback function.
When the function executes, it spits out an alert message with the passed values displayed. Then it executes the callback function.

Notice that the actual parameter is just “callback” (without parentheses), but then when the callback is executed, it’s done using parentheses. You can call this parameter whatever you want, I just used “callback” so it’s obvious what’s going on.

The callback function itself is defined in the third argument passed to the function call. That code has another alert message to tell you that the callback code has now executed. You can see in this simple example that an argument passed into a function can be a function itself, and this is what makes callbacks possible in JavaScript.