8.1. Writing a Handler

Some notable differences exist between AppleScript handlers and the functions you may be used to writing in other programming languages. I point out these differences as you work through this chapter.

The purpose of the handler in the following Try It Out is simply to write a message to the Event Log.

8.1.1.

8.1.1.1. Try It Out: Writing Your First Handler

In this program, you get your feet wet by writing a simple handler.

  1. Type the following program into Script Editor:

    -- Simple handler to log a message
    
    on logMsg()
        log "This is from the logMsg handler"
    end logMsg
    
    -- Test out the handler
    
    logMsg()
    
    -- Call the handler five more times
    repeat 5 times
        logMsg()
    end repeat
  2. Click the Event Log tab and run the program. You see the following recorded in the Event Log:

    (*This is from the logMsg handler*)
    (*This is from the logMsg handler*)
    (*This is from the logMsg handler*)
    (*This is from the logMsg handler*)
    (*This is from the logMsg handler*)
    (*This is from the logMsg handler*)
8.1.1.2. How It Works

You define a handler in AppleScript by writing the keyword on followed by the handler's name. This, in turn, is followed by a comma-separated list of parameters or arguments that the handler takes, enclosed in a set of parentheses. If the handler takes no arguments, as is the case with your first handler, it uses just empty parentheses.

The statements that are part of the handler then follow on subsequent lines, up to the end statement, which closes the handler's definition. ...

Get Beginning AppleScript® 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.