Previous Page
Next Page

9.8. The Run Handler

The run handler of a script object (or script) has been discussed in "Code and the Run Handler" in Chapter 6 and "Run Handler" in Chapter 8. The run handler is an event handler. Thus it has event handler syntax; it takes no parentheses, either in the definition or in the call.

It turns out that an explicit run handler may take parameters . This ability is useful only under special circumstances, and in fact it prevents the script object (or script) from running at all under normal circumstances, because you usually have no way to supply these parameters in the call.

The official syntax for defining a run handler with parameters is to express all parameters as a single list. For example:

script s
    on run {what, what2}
        display dialog what & space & what2
    end run
end script

You can't simply tell that script object to run, because you can't supply the parameters. If you try, you'll get an error at runtime:

run s -- error: «script s» doesn't match the parameters {what, what2} for run

One solution is to use the run script command, which permits parameters to be passed to a run handler:

run script s with parameters {"howdy", "there"}

That approach is rather extreme; run script is expensive , because it requires the creation (and destruction) of an entire separate instance of the AppleScript scripting component. A clever and inexpensive approach (which I owe to Michael Terry) is to take advantage of script object inheritance (Chapter 8) and the continue command, which can pass parameters to any event:

property args : null
script s
    on run {what, what2}
        display dialog what & space & what2
    end run
end script
script trampoline
    property parent : s
    continue run args
end script
set args to {"howdy", "there"}
run trampoline

If you give your script as a whole an explicit run handler that expects parameters, you won't be able to run your script in the Script Editor or in most script runners. For example:

on run {what}
    display dialog what
end run

That's an unrunnable script, unless you have some way to supply the parameter. One approach is to save the script as a compiled script file and then use run script to run the file along with a parameter.

Clearly a run handler with parameters is an oddity, but there are circumstances where it is useful. For example, an Automator action's script has a run handler that takes parameters (see Chapter 27).


Previous Page
Next Page