Section 9.3. Handlers as Values


9.3. Handlers as Values

A handler is a datatype in AppleScript. This means that a variable's value can be a handler. In fact, a handler definition defines exactly such a variable. You can refer to this variable, and get and set its value, just as you would any other variable. Here, we fetch a handler as a value and assign it to another variable:

 on sayHowdy( )     display dialog "Howdy" end sayHowdy set sayHello to sayHowdy sayHello( ) -- Howdy

As the example shows, after the assignment of the handler to another variable, we can call that variable as if it were a handler. That's because the variable is a handler.

You can also assign a new value to a variable whose value is a handler. No law says that this new value must be another handler; you're just replacing the value of the variable, as with any other variable. The original handler functionality is lost. For example, you could do this if you wanted:

 on sayHowdy( )     display dialog "Howdy" end sayHowdy set sayHowdy to 9 display dialog sayHowdy -- 9

You can assign to a variable whose value is a handler the value of another handler, in effect replacing its functionality with new functionality. Of course, that functionality has to be defined somewhere to begin with, and the old functionality is lost. For example:

 on sayHowdy( )     display dialog "Howdy" end sayHowdy on sayGetLost( )     display dialog "Get Lost" end sayGetLost set sayHello to sayGetLost sayHello( ) -- Get Lost

An elegant use of this feature is a list that acts as a dispatch table . The idea is that sometimes we want to call one handler and sometimes another, depending on the circumstances. Rather than code the handler calls within a branching construct, we make a list of handlers and call the desired item of the list:

 on sayHello( )     display dialog "Hello" end sayHello on sayGetLost( )     display dialog "Get Lost" end sayGetLost set L to {sayHello, sayGetLost} -- for this example, we decide randomly which one to call set h to item (random number from 1 to 2) of L h( )




AppleScript. The Definitive Guide
AppleScript: The Definitive Guide, 2nd Edition
ISBN: 0596102119
EAN: 2147483647
Year: 2006
Pages: 267
Authors: Matt Neuburg

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net