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.
Handler Definition
A handler is defined using a block with the keyword on
:
onhandlerName
( ) -- 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 ...
Get AppleScript: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.