Callback and Functions in jQuery

Unlike many other programming languages, JavaScript enables you to freely pass functions around to be executed at a later time. A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.

Callbacks are special because they patiently wait to execute until their parent finishes. Meanwhile, the browser can be executing other functions or doing all sorts of other work.

Callbacks without Arguments

If a callback has no arguments, you can pass it as given below:

$.get( "myhtmlpage.html", myCallBack );
When $.get() finishes getting the page myhtmlpage.html, it executes the myCallBack() function.
Note: The second parameter the function name (but not as a string, and without parentheses).

Callback with Arguments
Executing callbacks with arguments can be slightly tricky as shown below:

WRONG Code

$.get( "myhtmlpage.html", myCallBack( param1, param2 ) );

This code will not work because the code executes myCallBack( param1, param2 ) immediately and then passes myCallBack()'s return value as the second parameter to $.get().
Our intention is to pass the function myCallBack(), not myCallBack( param1, param2 )'s return value (which might or might not be a function).

RIGHT Code

An anonymous function can be used as a wrapper to defer executing myCallBack() with its parameters.
Notice the use of function() {.
The anonymous function does exactly one thing: calls myCallBack(), with the values of param1 and param2.

$.get( "myhtmlpage.html", function() {
    myCallBack( param1, param2 );
});

When $.get() finishes getting the page myhtmlpage.html, it executes the anonymous function, which executes myCallBack( param1, param2 ).

No comments:

Post a Comment