I'm currently writing JavaScript and confusing about callback. I've found it's not kind of built-in functions though...
I'm now reading O'Relly JavaScript 5th Edition and it shows a sample code something like below:
getText = function(url, callback) // How can I use this callback? { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { callback(request.responseText); // Another callback here } } request.open('GET', url); request.send(); }
Basically, I suppose I don't understand the general idea of callback
though... Could someone write a sample code to take advantage of callback
above?
The function that takes another function as an argument is called a higher-order function. According to this definition, any function can become a callback function if it is passed as an argument. Callbacks are not asynchronous by nature, but can be used for asynchronous purposes.
Asynchronous callbacks are functions passed to another function that starts executing code in the background. Typically, when the code in the background finishes, the async callback function is called as a way of notifying and passing on data to the callback function that the background task is finished.
Callback functions have access to both their own scope plus the scope of the code that calls them plus the global scope of the calling code. So callback functions are handier to manage codewise, especially in larger JS applications where data is passed across several module boundaries during execution of a task.
To write a callback function as a named function: Create an XMLHttpRequest object in the global scope (outside of the following two functions). var xmlhttp = new XMLHttpRequest(); Write a function to use as the callback function. Set the value of the onreadystatechange property to the name of the function.
Callbacks are pretty simple and nifty! Because of the nature of AJAX calls, you don't block execution of your script till your request is over (it would be synchronous then). A callback is simply a method designated to handle the response once it gets back to your method.
Since javascript methods are first class objects, you can pass them around like variables.
So in your example
getText = function(url, callback) // How can I use this callback? { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { callback(request.responseText); // Another callback here } }; request.open('GET', url); request.send(); } function mycallback(data) { alert(data); } getText('somephpfile.php', mycallback); //passing mycallback as a method
If you do the above, it means you pass mycallback
as a method that handles your response (callback).
EDIT
While the example here doesn't illustrate the proper benefit of a callback (you could simply put the alert in the onReadyStateChange function after all!), re usability is certainly a factor.
You have to keep in mind that the important thing here is that JS methods are first class objects. This means that you can pass them around like objects and attach them to all sorts of events. When events trigger, the methods attached to those events are called.
When you do request.onreadystatechange = function(){}
you're just assigning that method to be called when the appropriate event fires.
So the cool thing here is that these methods can be reused. Say you have an error handling method that pops up an alert and populates some fields in the HTML page in the case of a 404 in the AJAX request.
If you couldn't assign callbacks or pass methods as parameters, you'd have to write the error handling code over and over again, but instead all you have to do is just assign it as a callback and all your error handling will be sorted in one go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With