Power Handler Tricks

A handler takes values as parameters and returns a value. A handler is a value. A script object is a value and can contain a handler. If these facts suggest to your mind an intimation of amazing possibilities, read on.

Handler and Script Object as Parameter

You can pass a handler as a parameter to handler. The difficulty is in calling it. This code fails with a runtime error:

on sayHowdy( )
    display dialog "Howdy"
end sayHowdy
on doThis(what)
    what( )
end doThis
doThis(sayHowdy) -- error: «script» doesn't understand the what message

The trouble is that AppleScript refuses to identify the what( ) in the handler call with the what that arrived as a parameter. This is actually another case of the rule (see "Handler Calls, Commands, and Script Objects" in Chapter 8) that an unqualified handler call is a message directed to the current script object, which in this case is the script as a whole.

One possible workaround is to use a global. This approach works because by copying the handler to a global we're putting it where a message directed to the script as a whole can find it (see "Scope of Globals" in Chapter 10):

on sayHowdy( )
    display dialog "Howdy"
end sayHowdy
on doThis(what)
    global what2
    set what2 to what
    what2( )
end doThis
doThis(sayHowdy) -- Howdy

This solution is clever, but now we've broken encapsulation. Global variables pose risks (other code might access this same global, or we might be tromping accidentally on some other code's global), and besides, if we're ...

Get AppleScript: The Definitive Guide, 2nd Edition 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.