Handler Calls

A handler call is special, because it is a kind of message. (See Section 8.5.1.) This message is directed to a particular target—a script object. If no target is specified explicitly, the target is the script object in which the handler call appears.

When a script object receives a handler call message, the handler is sought as a name defined as a top-level entity within it (that is, not a free variable and not a local variable). If there is no such name, the search passes to the script object’s parent; this is the top-level script by default, though it can be changed (Section 9.7, later in this chapter).

In this example, the handler call is directed implicitly; the call appears within myScript so it is directed to myScript, which defines a handler by the right name:

script myScript
        on myHandler(  )
                display dialog "Howdy"
        end myHandler
        myHandler(  )
end script
run myScript -- Howdy

This example doesn’t work, because myHandler isn’t defined in myScript:

script outerScript
        on myHandler(  )
                display dialog "Howdy"
        end myHandler
        script myScript
                myHandler(  )
        end script
end script
run outerScript's myScript -- error

This example works, because we specify the correct target explicitly:

script outerScript
        on myHandler(  )
                display dialog "Howdy"
        end myHandler
        script myScript
                outerScript's myHandler(  )
        end script
end script
run outerScript's myScript -- Howdy

This works even though myHandler isn’t defined in myScript:

script myScript myHandler( ) end script on myHandler( ) display dialog ...

Get AppleScript: The Definitive Guide 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.