JQuery Callback and Functions

 A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.

 

The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes.

 

Another important thing to know is how to properly pass the callback.

 

 

Callback without arguments

 

For a callback with no arguments you pass it like this:

 

 $.get('myhtmlpage.html', myCallBack);

 

Note that the second parameter here is simply the function name (butnot as a string and without parentheses).

 

Functions in Javascript are 'First class citizens' and so can be passed around like variable references and executed at a later time.

 

 

Callback with arguments

 

"What do you do if you have arguments that you want to pass?", you might ask yourself.

 

Wrong

The Wrong Way (will not work!)

 

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


This will not work because it calls

 

myCallBack(param1, param2)

 

and then passes the return value as the second parameter to $.get()

 

Right

The problem with the above example is that myCallBack(param1, param2) is evaluated before being passed as a function.

 

Javascript and by extension jQuery expects a function pointer in cases like these. I.E. setTimeout function.

 

In the below usage, an anonymous function is created (just a block of statements) and is registered as the callback function.

 

Note the use of 'function(){'. The anonymous function does exactly one thing: calls myCallBack, with the values of param1 and param2 in the outer scope.

 

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

 

param1 and param2 are evaluated as a callback when the '$.get' is done getting the page.

 

 

 

發佈了22 篇原創文章 · 獲贊 22 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章