I now what's a callback fn and how it works, but I don't seem to understand how it gets called in jQuery, for example:
$('#btn').click(function(){
alert('Test');
});
I know that when the click method had finished executing, then the callback fn gets called, but I just don't understand how is that anonymous callback fn called.
In this example:
function Greeting(function(){alert('Callback fn inside Greeting');}){
alert('Inside Greeting fn');
}
I'd assume that after the alert inside Greeting had been display, THEN my callback fn will get called, but it doesn't. I just see this error "uncaught syntax error: unexpected token function". My question is, how do I call the anonymous callback fn that I have as a parameter in Greeting fn? Thanks in advance.
You need to do 2 things separately:
In your second example, you're doing both at the same time - you need to separate them. Here's how you'd do it:
// Step 1: Define the function that takes an anonymous callback
function Greeting(callback) {
console.log("inside Greeting! About to call callback.");
callback(); // Actually call the callback function.
console.log("Finished calling callback");
}
// Step 2: Call that function with the anonymous callback
Greeting(function() { console.log("This is the anonymous function."); });
The output of that code is:
inside Greeting! About to call callback.
This is the anonymous function.
Finished calling callback
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.