Reputation: 11
Why does callback function passed in the form anonymous function for event handler ensure that callback function will execute after the callee function has executed?
So my question is:
Case 1:
$.get( "myhtmlpage.html", myCallBack( param1, param2 ) ); //this wont work
Case 2:
$.get( "myhtmlpage.html", function() { // will execute $.get and then myCallBack
myCallBack( param1, param2 );
});
Why is it the case?
Upvotes: 1
Views: 1188
Reputation: 59
myCallBack( param1, param2 )
This is a function call, not a function statement, while you need a function as a parameter for $.get()'s second parameter.
You can also
$.get( "myhtmlpage.html", myCallBack);
Upvotes: 0
Reputation: 339816
At its core, JavaScript is a single threaded language with every action triggered by an event.
The browser waits around in an "event loop" for events to happen (e.g. user input device events, timer events, AJAX events, etc) and for each event it will call any registered event handlers (i.e. callbacks) that have been registered on that event.
Once the event handler has finished its work, return passes back to the "event loop".
So, when you call $.get()
the jQuery library internally creates an XMLHttpRequest
object and registers the supplied callback function as the event handler.
That function is not called immediately. Any other code following the $.get()
is run, and then control goes back to the event loop again.
Eventually, the XMLHttpObject
will create an onreadystatechange
event and add it to the queue of events waiting to be processed.
The event loop will see that event, find the registered callback, and invoke it.
Simples :)
Upvotes: 1