0

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.

1
  • 1
    That's because function Greeting(this section is used to pass arguments/values) into the function. Commented Mar 9, 2015 at 1:41

1 Answer 1

3

You need to do 2 things separately:

  1. Define the function that takes an anonymous callback
  2. Call that function, and pass in the callback.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.