In Head First Ajax, they give the following example:
function getDetails(itemName) {
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "getDetails.php?ImageID=" + escape(itemName);
request.open("GET", url, true);
request.onreadystatechange = displayDetails;//This references the function below
request.send(null);
}
function displayDetails() {
if (request.readyState == 4) {
if (request.status == 200) {
detailDiv = document.getElementById("description");
detailDiv.innerHTML = request.responseText;
}
}
}
I’m curious what kind of construction is request.onreadystatechange = displayDetails;. The book says that “this is a reference to a function, not a function call”. However I don’t understand what this really means. I suppose it assigns the displayDetails function to the object request.onreadystatechange, but I don’t understand why or when to use this construction.
For example, what is the advantage of using this construction rather than doing something like:
request.onreadystatechange = function () {
if (request.readyState == 4) {
if (request.status == 200) {
detailDiv = document.getElementById("description");
detailDiv.innerHTML = request.responseText;
}
}
}
Also, is that an example of a functional language feature?
Yes, that’s an example of a functional language feature. Functions are first-class citizens on those languages, meaning they can also be passed around, assigned to variables, etc.
About your question on
eventhandler = function () { }versuseventhandler = somefunc, you said:The
requestobject has a property calledonreadystatechange, which represents an event handler function that should be called when the request’sreadyStateproperty changes. That’s why the book said it’s not a function call, but a reference assignment. You’re not calling the function when you assign it torequest.onreadystatechange, it will be called only when that event happens. Clicks and all other events work like that (they’re basically asynchronous).It makes sense to use a function reference instead of an anonymous function assigment if you want to use the same handler for more than one event. For example, if you have two “save” buttons on two different parts of a web page, you can assign the same handler function to their click events.