Next page | Contents page |

Crucial: Javascript is event-driven

Many different kinds of events can occur in a computer system. The most common ones we will be dealing with are users clicking mouse buttons or typing on a keyboard. We will also consider time events: we can set something like an alarm to cause something to happen later.

It is really important to understand the implications of the event process. See the note in green at the foot of this page.

We have seen one kind of event already, onload and we told the browser that when this event occurs it should start our program by invoking the function run. This is the general pattern: for any kind of event we say which function should be used. Our function will then be an "event listener" and the browser will give our function one parameter which is a reference to an object describing the event.

There is a pattern like this:


	event  ->  our function  ->  refresh screen  ->  stop

To set this up we use a method which all objects representing HTML elements possess:


	cnv.addEventListener("click", handleClick);

"click" means a mouse click. Notice that we are giving just the name of our handleClick function - there are no brackets so it is not being invoked here.

addEventListener() would probably be done once at the start, in run() where we have cnv referencing the canvas element. Then we would write a function to be the listener:


	function handleClick(e)
	{
		// whatever we want to do
		// real examples later
	}

The parameter e is a reference to an object giving details of the event, such as where the mouse cursor was when the mouse was clicked. That enables the user to point to precise positions in the canvas.

It is really important to understand the implications of the pattern shown above. Drawings only become visible when the process ends: the refresh screen step. Drawing really happens in a hidden copy of the canvas which is only switched to the display when the process ends. This means that you cannot have a loop inside the event listener to show any kind of animation. That is why we will need time events, to be covered later.
Next page | Contents page |