A computer program responds to a mouse click by running a function.
Here is an example of an event handler function:
f = (e) -> moveto e click f
Try it out. What does it do?
1. The function (e) -> moveto e
takes one input e
,
and then it does one action: it
moves the turtle to the location of the object
e
. That function is given the
name f
by
f = (e) -> moveto e
.
Any name would work fine.
2. The command click f
tells the
computer to call f
whenever
the user clicks the mouse.
3. Every time you click, the computer
creates an "Event" object representing the
mouse click position, and it runs the
function f
, passing the mouse
click event as input.
Programmers often skip the step of giving
a name to a function. We can just define
the function directly and give it to the
click
command without naming it.
This code does the same thing as the above
code, but it doesn't assign a name to
the function:
click (e) -> moveto e
There are other types of events. For example,
each time the mouse moves, the computer can
call a function each time the mousemoves
by the command mousemove f
.
Mousemove events happen very quickly, so
to keep up with them, it is a good idea to
move the turtle quickly with
speed Infinity
.
speed Infinity mousemove (e) -> moveto e click (e) -> pen random color