8.2. Passing Parameters to Handlers

The logMsg handler is not very flexible. Each time it is called, it writes the same string to the Event Log. You may want to have handlers that perform very specialized tasks like this. More often, you'll want to write handlers that perform different actions based on values supplied as arguments or parameters.

The terms argument and parameter are used interchangeably when speaking about handlers in this chapter.

The next Try It Out program extends the usefulness of the logMsg handler by allowing the caller to specify precisely what message he wants added to the Event Log.

8.2.1.

8.2.1.1. Try It Out: Passing Parameters to Handlers

In the following program, you see how to pass a parameter to a handler.

  1. Type the following program into Script Editor:

    --  Handler to log a message given as its parameter
    
    on logMsg(theMsg)
        log theMsg
    end logMsg
    
    -- Test out the handler
    
    logMsg("Log this message")
    
    -- Call the handler five more times
    
    repeat with i from 1 to 5
        set theArg to "Message Number " & (i as string)
        logMsg(theArg)
    end repeat
  2. Click the Event Log tab and run the program. You should see the following in the Event Log pane:

    (*Log this message*)
    (*Message Number 1*)
    (*Message Number 2*)
    (*Message Number 3*)
    (*Message Number 4*)
    (*Message Number 5*)
8.2.1.2. How It Works

This time you want to pass a value to the logMsg handler, so you define your handler like this:

on logMsg(theMsg)
    log theMsg
end logMsg

Inside the parentheses, you list the parameter ...

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.