Pages

Callback with JavaScript

We are about to see a way to get a better separation between our JavaScript code from the HTML body.

Instead of relying on the onXXX tag attributes, we can access the even handlers from the inside of the script tag, leaving the HTML body cleaner and easier to maintain.

To do that we use the callback mechanism, that require us to manage the function address as a variable. Good news is that it quite easy to be done with JavaScript.

The basic fact is that we can see onload, that we have previously accessed as attribute of the body tag, as property of the JavaScript object "window". So we can actually use it to react on the event signalling the page has been completely loaded.

The twist is that we should put in it not a string but the address of a function that we want to be called. Luckly that is pretty easy to be done in JavaScript: just remove the brackets. So, if we had that:
<body onload="greet()"><!-- ... --->
In a script tag, we can write this:
window.onload = greet;

Actually, there is another thing. The event handler expects to be given the address of a function that accept one parameter, a so called object event. But JavaScript is a very permessive language, and there is no complain for passing something different. In any case, to avoid misunderstanding, it would be better to explicitely show that parameter in the definition of the called function, even if it is not used:

function greet(evt) {
// ...
}

It is handy sometimes using an anonymous function. Obviously this makes sense only for a function that has to be used once, like could be one that is used as callback for an event handler. And actually is typical to a piece of code like this:

window.onload = function(evt) {
// ...
}

Here the anonymous function, accepting in input an object event, represents the code that would be called as callback when the page is loaded. At that moment the JavaScript code has access to the elements defined in the page body.

So, we put inside this function all the connection between the HTML and the JavaScript. In a way, this is a sort of constructor for the script.

For instance, let's say that we have this element in the HTML body:

<div style="margin-top:100px; text-align:center">
<img id="rock" src="image1.png" alt="Bored" style="cursor:pointer" />
</div>

And we want that clicking on that element would result calling:

function comment(index) {
alert("You are accessing item " + index);
}

passing as index 42.

Instead of using the HTML attribute onclick in the element tag, we could write our onload callback function in this way:

window.onload = function(evt) {
document.getElementById("rock").onclick = function(evt) { comment(42); };
}


More on JavaScript functions in chapter six of Head First JavaScript.

No comments:

Post a Comment