JQuery Callback and Functions

來源:互聯網
上載者:User

 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.

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.