callback,字面上的解釋就是「回呼」,這牽涉到多工作業系統中兩個同時執行﹝cocurrent﹞的不同模組。一種情形是,A 模組給 B 模組一個 function pointer,
請它在處理完某項工作後,或是在適當時機,使用這個 function pointer 來呼叫該函式。例如,A 模組裡面寫了一個 CallMeIfDone 的 function,然後它啟動了
B 模組,並且把 CallMeIfDone 的位址傳給 B 模組。A 模組繼續執行它的工作,B 模組也同時在處理它的事情,等到 B 模組處理完畢,它就會呼叫 CallMeIfDone,
但是這個函式是寫在 A 模組裡面的,所以實際上是跑回來 A 模組的地盤執行 CallMeIfDone,因此就稱為「回呼,callback」。另一種情形是,B 模組是一個獨立
執行的模組,專門處理使用者輸入,每當使用者敲一下鍵盤,或是動一下滑鼠,它就會產生一個事件,需要處理這些事件的其他模組必須向 B 模組登記
callback function,例如 A 模組向 B 模組登記了 KeyboardEvents 的 callback function,那麼 B 模組在偵測到鍵盤動作時,就會去呼叫這個函式了,當然這個
函式也是寫在 A 模組裡面的。
A callback function is a function which is:
- passed as an argument to another function, and,
- is invoked after some kind of event.
Once its parent function completes, the function passed as an argument is then called.
Pseudocode:
// The callback method
function meaningOfLife() {
log("The meaning of life is: 42");
}
// A method which accepts a callback method as an argument
// takes a function reference to be executed when printANumber completes
function printANumber(int number, function callbackFunction) {
print("The number you provided is: " + number);
}
// Driver method
function event() {
printANumber(6, meaningOfLife);
}
Result if you called event():
The number you provided is: 6
The meaning of life is: 42
Reference:
http://www.programmer-club.com.tw/ShowSameTitleN/c/20869.html
https://stackoverflow.com/questions/824234/what-is-a-callback-function