views:

191

answers:

3

Hi

I got acquainted with jQuery a few days back and am beginning to realize the little magic it can do.

I am curious to know how exactly a callback with arguments is executed in jQuery i.e. what is the exact execution sequence?

I went through the link http://docs.jquery.com/Tutorials:How_jQuery_Works

and it speaks of a wrong way i.e.

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

and a right way i.e.

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

In the first case, myCallBack would be executed first and then its return value would act as an argument to get. In the latter method, get would return a web page which would be acted upon by the myCallBack.

How does it work as syntactically both have myCallBack as being still an argument to get? I'm a bit confused on this.

cheers

+2  A: 

This is indeed quite a vague example. You should write:

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

That is because internally jQuery does something like this(very simplified):

$.get = function(url, callback){
  //make call to url
  //when completed execute callback:
  callback(param1, param2);
}

You could also write:

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

That will also call myCallBack with the two parameters.

Pim Jager
+1  A: 

In the first instance, myCallBack(param1, param2) gets evaluated and executed immediately. In this syntax it will be called before $.get() is called.

In the second instance, an unnamed, anonymous, function is defined which encloses myCallBack() for later use. It is stored as a parameter to $.get() and will be fired ONLY AFTER $.get() is called.

For more information on callbacks, see Callback (computer science) at Wikipedia.

artlung
A: 

If you use this syntax:

myCallBack(param1, param2)

What you're doing is calling the function and getting the result, just like any other time you would call a function.

If you use this syntax:

myCallBack

You aren't calling the function, but mentioning the function, which is why this syntax can be used to pass myCallBack as a callback function.

The third way:

function(){myCallBack(param1, param2);}

Will create a new, unnamed function that consists of a call to myCallBack. This can be passed into a function call or assigned to a variable.

As an aside, you should be careful using this syntax in the way that you did in the example, because in this case param1 and param2 are not bound by the anonymous function, and will be either blank or populated with values from the containing scope.

Dan Monego