Section 9.1. Handler Definition

9.1. Handler Definition

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

 on handlerName( )     -- commands within the handler end handlerName

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 thata 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.

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.

AppleScript. The Definitive Guide
AppleScript: The Definitive Guide, 2nd Edition
ISBN: 0596102119
EAN: 2147483647
Year: 2006
Pages: 267
Authors: Matt Neuburg

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: