Chapter 9. Handlers

A handler is a subroutine within a script. A handler is an important form of flow control, and leads to better-behaved, better-organized, more reusable, and more legible code. With a handler, the same code can be executed from different places in a script. Even if a handler is going to be called only once in the course of a script, it's a useful organizational device because it names a block of code, and this name can describe the block's purpose.

A handler is defined using a block with the keyword on:

on handlerName( )
    -- commands within the handler
endhandlerName

A synonym for on is to.

What follows the name of the handler in the on line of the block might be parentheses, but it might not. The real story is complicated; the details appear later in this chapter ("Syntax of Defining and Calling a Handler").

A handler definition may appear only at the top level of a script object (or a script as a whole). It is a top-level entity of the script object ("Top-Level Entities" in Chapter 8). It functions as a scope block . (The rules of scope appear in Chapter 10.) Read Chapter 6 for an overview of how script object definitions fit into a script's overall structure.

A handler definition is just that—a definition. Merely encountering a handler definition in the course of execution does not cause the handler to be executed. Rather, a handler definition is a form of variable definition. So, for example:

on sayHowdy( )
    display dialog "howdy"
end sayHowdy

That code does not cause a dialog to display. It defines a handler whose code, if executed, would display a dialog. The handler itself is the value of a variable. Here, that variable is sayHowdy; when this code is encountered, the variable sayHowdy is defined and initialized, and its initial value is the handler described by this block of code.

What causes a handler's code to run is code that calls the handler. This looks essentially like using the handler's name, with some special syntax that signifies you're actually calling and not merely mentioning the name of the variable that contains the handler. So, for example:

on sayHowdy( )
    display dialog "howdy"
end sayHowdy
sayHowdy( )

That code first defines a handler, then calls it. The call is in the last line. Because of that last line, the code does cause a dialog to be displayed.

Warning

It is not an error to refer to a handler by its name alone, with no parentheses or parameters. This can be a useful thing to do, if you wish to refer to the handler as a value (see "Handlers as Values," later in this chapter); but it doesn't call the handler. If you refer to a handler by its name alone, intending to call it, your script will misbehave in ways that can be difficult to track down.