I have been programming in different languages. Recently, I got an opportunity to start to know jQuery
. I was reading about call back functions and I understood what it meant(for doing things in a particular manner, one after the other.) I am a bit confused either to relate them with nested functions or not? Isn't it the same thing? Please help out to clear the concept. Thanks.
A callback function is any function which is invoked when an operation is complete. It doesn't really matter where it was defined: you can create a locally scoped function, a globally scoped, etc.
Using $.ajax
as an example, where success
is the callback:
function handleSuccess(data) {
$(document.body).append(data);
}
function doAjaxCall() {
$.ajax({url: 'some/path', success: handleSuccess });
}
is functionally equivalent to:
function doAjaxCall() {
var handleSuccess = function(data) {
$(document.body).append(data);
}
$.ajax({ url: 'some/path', success: handleSuccess });
}
is functionally equivalent to:
function doAjaxCall() {
$.ajax({ url: 'some/path', success: function(data) {
$(document.body).append(data);
}
});
}