HTML and CSS Reference
In-Depth Information
The anonymous function declaration must begin with the function keyword, which must
be followed by closed parentheses. The parentheses can include zero or more parameters.
The parentheses are followed by closed braces in which the code block that makes up the
implementation of the function is coded.
The only difference between an anonymous function and a named function is the name
portion of the function signature. That the anonymous function accepts parameters is an
important concept when dealing with callbacks.
When working with an API, either your own or a third party's, functionality often is
provided that includes the use of callbacks. As discussed earlier, callbacks are functions that
are processed when the transfer of control returns to the caller. For example, in the previous
section using jQuery with AJAX, the following code sample was used:
$.ajax({
url: searchPath,
cache: false,
dataType: "xml",
error: function(hdr, num, txt){…}
success: function (data) {
}});
In this sample, the AJAX call enables you to specify some functions to call back for dif-
ferent circumstances that can occur. The error and success properties allow you to specify
a function that the AJAX framework calls after it either successfully completes the request
or encounters an error. In each case, parameters are specified to receive the data that
accompanies each callback.
Callback functions can also be used in the form of a parameter to another function. Con-
sider the following example that accepts a user's input to evaluate if a score is a pass or a fail:
$("document").ready( function () {
$("#Button1").click( function () {
DoLongTask($("#inputValue").val(),
function (result, data) {
if (result == "SUCCESS")
alert(data + " is a Success");
else
alert(data + " is a fail");
});
});
} );
function DoLongTask(n,f)
{
if (n < 10)
f("SUCCESS", n);
else
f("FAIL", n);
}
Search WWH ::




Custom Search