TweetFollow Us on Twitter

An Introduction to Handlers

Volume Number: 21 (2005)
Issue Number: 2
Column Tag: Programming

AppleScript Essentials

by Benjamin S. Waldie

An Introduction to Handlers

In a previous article, you may remember that we discussed methods of writing AppleScripts to watch folders for incoming items to process. In each of the methods we discussed, we made use of handlers. This month, we are going to explore handlers in more depth. Since handlers are a fairly complex subject, the full scope of handlers will not be covered in this month's article. Rather, we will cover the basics of handlers. In future articles, we will discuss handlers in more detail.

What is a Handler?

A handler is a group of one or more AppleScript statements that are associated with a single command. As we will discuss, some handlers are user defined, and some are application, or system defined.

Once the command associated with a handler is invoked, the statements within that handler will execute. Handlers allow you to group your code into logical "chunks," which may be triggered, or called, over and over again within a script. By carefully constructing your handlers, you can make scripts very modular, giving you the ability to break the scripts apart and reuse the handlers again in future scripts. Many AppleScript developers store their handlers in code libraries. These libraries can then be loaded, and handlers within them can be triggered from other scripts.

Anatomy of a Handler

Let's take a look at a basic handler. The following handler may be used to display a basic dialog message.

on displayDialog()
   display dialog "This is code within a handler."
end displayDialog

Now, let's break handlers down into different parts, and examine how they are constructed.

Handler Definition

A handler definition refers to the handler itself. The following would be considered the handler definition from the previous example.

on displayDialog()
   display dialog "This is code within a handler."
end displayDialog

A handler definition always begins with the word on or to, which indicates to AppleScript that it is the beginning of a handler. In the example above, I chose to begin my handler with the word on. However, the method you choose to use is entirely at your discretion. You should use whichever word looks more acceptable to you.

The next part of the handler definition is the name of the handler, followed by any parameters to be passed to the handler by the script. For example:

displayDialog()

In many cases, you may need to pass information to a handler to be processed. To allow for this, handlers support input parameters. Handlers also have the ability to return data back to the script. For example, a handler may return a true/false value indicating whether or not it was successfully processed.

There are a couple different methods that you can use to specify input parameters, and we will discuss them shortly. In the previous example, the empty parentheses indicate that my handler does not require any parameters.

Following the first line of a handler definition are any AppleScript statements that should be executed by the handler. You may write as few or as many statements as you need, keeping in mind that they will not execute until the handler is called.

The final line of a handler definition always begins with the word end, followed by the name of the handler.

end displayDialog

To save time when writing a handler, you may write the word end, and when you compile your code, the handler name will automatically be inserted for you.

Handler Call

To call a handler from within a script, you must specify the name of the handler, followed by values for all of its parameters. The following is the call for the previous handler example:

displayDialog()

We'll look at calling handlers that use parameters shortly, as we explore parameters.

If you need to call a handler from within an application tell block, you must specify of me after the handler call, to indicate that the handler is to be addressed within the script, and not within the application. For example:

tell application "Finder"
   displayDialog() of me
end tell

Parameters

As previously mentioned, the first line of a handler contains the handler name, followed by any parameters to be passed into the handler. A parameter is a variable that is named in the handler definition, and is assigned a value when the handler is called. When calling a handler, all parameters are required, and must be specified. Handlers do not allow optional parameters.

There are two types of parameters that may follow a handler name - labeled parameters and positional parameters.

Labeled Parameters

Labeled parameters are parameters that are associated with labels in the handler definition. When the handler is called, these labels are used to determine which parameters are which. Therefore, when working with labeled parameters, you may pass the parameters through your handler call in any order you wish, so long as they correspond with the correct labels. The exception to this rule is that, in some cases, you may choose to assign a direct parameter, which is required to fall immediately after the handler name.

There are two ways that you can assign labeled parameters in a handler. The first is to assign the parameters using one of the following predefined labels: about, above, against, apart from, around, aside from, at, below, beneath, beside, between, by, for, from, instead of, into, on, onto, out of, over, since, through, thru, under. The label of may also be used, though only to define a direct parameter. If you add a direct parameter, using the label of, then you are required to have at least one or more additional parameters. The following is an example of a handler with labeled parameters:

to displayDialog of theText above theButtons aside from theIconNumber
   display dialog theText buttons theButtons with icon theIconNumber
end displayDialog

In the example above, the parameter theText is a direct parameter, as indicated by the label of. The parameter theButtons is associated with the label above, and the parameter theIconNumber is associated with the label aside from. The handler above would be called using the following line of code:

displayDialog of "Hello" above {"OK"} aside from 1

Again, since labeled parameters are associated with their labels, then you can rearrange the non-direct parameters, if desired. For example, the following handler call would function identically as the previous one:

displayDialog of "Hello" aside from 1 above {"OK"}

Another way to assign labeled parameters is to use custom labels. This is done by creating label definitions in the format labelName:parameterName, separating them by commas, and preceding them with the label given. Custom labeled parameters must follow any predefined label parameters. An example of a handler with custom labeled parameters is the following:

to displayDialog of theText given someButtons:theButtons, someIconNumber:theIconNumber
   display dialog theText buttons theButtons with icon theIconNumber
end displayDialog

In the example above, the parameter theText is a direct parameter, preceded by a predefined label. The remaining parameters are custom labeled parameters. The parameter theButtons is associated with the custom label someButtons, and the parameter theIconNumber is associated with the custom label someIconNumber. This handler can be called using the following line of code:

displayDialog of "Hello" given someButtons:{"OK"}, someIconNumber:1

Again, since this handler makes use of labeled parameters, the non-direct parameters may be rearranged, if desired:

displayDialog of "Hello" given someIconNumber:1, someButtons:{"OK"}

Positional Parameters

Another type of parameter that you can use when defining a handler is a positional parameter. Positional parameters are separated by commas, and do not contain any labels. Because they do not contain labels, they are identified by their position in the handler definition. Therefore, they must be listed in the same position when the handler is called. The following is an example of a handler that makes use of positional parameters:

on displayDialog(theText, theButtons, theIconNumber)
   display dialog theText buttons theButtons with icon theIconNumber
end displayDialog

The handler above may be called using the following line of code:

displayDialog("Hello", {"OK"}, 1)

Return Value

In some cases, a handler may return a value to the script that called it. This value may be placed into a variable for later usage. By default, a handler will return the result of the last AppleScript statement that executes within the handler, assuming that this statement produces a result. If desired, you may configure your handler to return a different value. For example, the following code returns the name of the button clicked in the dialog.

set theChoice to displayDialog()

on displayDialog()
   display dialog "Would you like to continue processing?" buttons {"Yes", "No"}
   return button returned of result
end displayDialog

Next, I could add additional code at the root level of my script to check the button that was clicked, now stored in a variable called theChoice, and take the appropriate course of action.

Within a handler, you may return a value at any time to cease further execution of that handler, or you may return no value to cease execution without returning a specific value. For example, the following handler will stop processing, returning no value, if the user clicks the "No" button.

displayDialog()

on displayDialog()
   display dialog "Would you like to continue processing?" buttons {"Yes", "No"}
   set theChoice to button returned of result
   if theChoice = "No" then return
   display dialog "Continuing..."
end displayDialog

Types of Handlers

There are two types of handlers in AppleScript - subroutine handlers and command handlers.

Subroutine Handlers

Subroutine handlers are groups of statements, which are defined by the developer, and called throughout a script, or from another script. Subroutines can be extremely useful if you need to perform the same exact task over and over throughout your script. For example, let's say that you need to display an informational dialog to the user 10 times throughout your script to let the user know what is occurring.

display dialog "Beginning next task..." buttons {"*"} 
   default button "*" with icon 1 giving up after 3

To display the above dialog 10 times, I could write out all of this code 10 times - or, I could write a handler 1 time.

on displayNextTaskMessage()
   display dialog "Beginning next task..." buttons {"*"} default 
      button "*" with icon 1 giving up after 3
end displayNextTaskMessage

Once written, this handler can be triggered from anywhere within my script. Rather than writing the entire lengthy line of display dialog code each time I need to display the dialog to the user, I can call my handler instead. The following code would call the displayNextTaskMessage handler.

displayNextTaskMessage()

In the example above, you may be wondering where the handler name "displayNewTaskMessage" came from. This is something that I defined myself when writing the handler. Remember, since subroutine handlers are defined by a developer, their names are user definable. So, I could have named this handler anything I wanted, as long as it was not the name of another existing handler in my script.

Command Handlers

A command handler is a group of statements that is triggered by a specific application or system related event.

Every AppleScript application contains an implied run handler. Any AppleScript statements at the top level of the script, excluding global variables, properties, other handlers, and script objects, fall within that run handler. If you prefer to make the run handler visible in your code, you may wrap these statements within an on run handler call. When the script is run, both methods will behave identically. For example, each of the examples below will perform the exact same function:

Example 1:

display dialog "Hello!"

Example 2:

on run
   display dialog "Hello!"
end run

As you can see, any code within the run handler of a script will be executed whenever the script is run. However, in some cases, you may want to execute code when other types of actions occur within your script.

The open handler may be used to initiate specific code when items are dragged and dropped onto a script in the Finder. For example:

on open theDroppedItems
   -- Process the items
end open

By adding an open handler into a script, and then saving that script as an application, the script will automatically accept dropped files and folders. It will also receive a new icon, indicating that it is now a drop script.

In the previous example code, the parameter theDroppedItems will contain a list of paths to any items dropped onto the script. If you want your script to only process folders, then you would need to add custom code within the open handler to determine which dropped items were folders, and process only these items.

Two other types of command handlers that may be added to an AppleScript application are the idle handler and the quit handler.

An idle handler is particularly useful when creating stay open AppleScript applications. In a stay open AppleScript application, by default, AppleScript will send the script an idle command every 30 seconds. At that time, any code within the idle handler will execute. For example, if I save the following code as a stay opened AppleScript application, and trigger it, the script will beep every 30 seconds:

on idle
   beep
end idle

Though the default time period between idle messages is 30 seconds, I can change this behavior if desired, by returning an integer value indicating how many seconds of a delay should occur before the next idle. In the following example, the script would beep every 10 seconds.

on idle
   beep
   return 10
end idle

The quit handler may be used in order to execute code when the script quits, whether manually quit by the user or not.

on quit
   display dialog "Task complete."
end quit

Example Handlers

Now that we have covered the basics of handlers, let's take a look at some example handlers, which may be useful to you as you write scripts in the future. Each of these handlers has been written generically, so that you can use it in virtually any script in the future.

The following handler will make a new folder in a specified output folder, using a specified name:

on makeNewFolder(theNewFolderName, theOutputFolder)
   tell application "Finder" to make new folder at folder theOutputFolder with properties 
      {name:theNewFolderName}
end makeNewFolder

The following handler will delete a folder of a file:

on moveItemToTrash(theItemPath)
   tell application "Finder" to delete item theItemPath
end moveItemToTrash

The following handler will mount an afp volume:

on mountVolume(theVolumeName, theServerIPAddress, theUserName, thePassword)
   mount volume "afp://" & theUserName & ":" & thePassword & "@" & theServerIPAddress 
      & "/" & theVolumeName as string
end mountVolume

In Closing

Again, handlers are a fairly complex aspect of AppleScript development for many users. Today, I use them regularly, and I try to make them as modular as possible. My theory is that if I write code to perform a specific task, such as opening a document in QuarkXPress, then I don't want to ever write that code again. Rather, I store the handler for later usage in future scripts, and the next time I need to perform the task, which could be a year down the line, I simply add the handler into my new script.

I encourage you to begin using handlers more in your scripting, as it will benefit you greatly. We'll discuss other aspects of handlers in more detail in future articles. In the meantime, for additional information about handlers, you may want to check out an AppleScript book, or browse the AppleScript Language Guide at <http://developer.apple.com/documentation/AppleScript/>.

Until next time, keep scripting!


Benjamin Waldie is president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. In addition to his role as a consultant, Benjamin is an evangelist of AppleScript, and can frequently be seen presenting at Macintosh User Groups, Seybold Seminars, and MacWorld. For additional information about Benjamin, please visit http://www.automatedworkflows.com, or email Benjamin at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

iMazing 2.17.16 - Complete iOS device ma...
iMazing is the world’s favourite iOS device manager for Mac and PC. Millions of users every year leverage its powerful capabilities to make the most of their personal or business iPhone and iPad.... Read more
VueScan 9.8.22 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
MacPilot 15.0.2 - $15.96 (53% off)
MacPilot gives you the power of UNIX and the simplicity of Macintosh, which means a phenomenal amount of untapped power in your hands! Use MacPilot to unlock over 1,200 features, and access them all... Read more
Visual Studio Code 1.85.0 - Cross-platfo...
Visual Studio Code provides developers with a new choice of developer tool that combines the simplicity and streamlined experience of a code editor with the best of what developers need for their... Read more
Spotify 1.2.26.1187 - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
Transmission 4.0.5 - Popular BitTorrent...
Transmission is a fast, easy, and free multi-platform BitTorrent client. Transmission sets initial preferences so things "just work", while advanced features like watch directories, bad peer blocking... Read more
Fantastical 3.8.9 - Create calendar even...
Fantastical is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event details... Read more
Notion 3.0.0 - A unified workspace for m...
Notion is the unified workspace for modern teams. Features: Integration with Slack Documents Wikis Tasks Release notes were unavailable when this listing was updated. Download Now]]> Read more
GarageBand 10.4.10 - Complete recording...
GarageBand is the easiest way to create a great-sounding song on your Mac. Add realistic, impeccably produced and performed drum grooves to your song with Drummer. Easily shape the sound of any... Read more
Pacifist 4.1.0 - Install individual file...
Pacifist opens up .pkg installer packages, .dmg disk images, .zip, .tar. tar.gz, .tar.bz2, .pax, and .xar archives and more, and lets you extract or install individual files out of them. This is... Read more

Latest Forum Discussions

See All

Best iPhone Game Updates: ‘Bloons TD 6’,...
Hello everyone, and welcome to the week! It’s time once again for our look back at the noteworthy updates of the last seven days. We’re getting well into the month now, which means we’ll be seeing more holiday-themed updates this time. Only a couple... | Read more »
‘DOOM’ 30th Anniversary Stream Featuring...
id Software’s DOOM ($4.99) celebrated its 30th anniversary over the weekend. While I didn’t play it literally when it launched, I adored the shareware version I played hundreds of times until I finally got the full game. | Read more »
‘Shadowverse: Worlds Beyond’ Is a New Fr...
At its Shadowverse Next 2024 event, Cygames announced Shadowverse: Worlds Beyond for iOS, Android, and PC. This new game will have many new features including a lobby system that allows you to play Mahjong, go fishing, and more. If you ever wanted... | Read more »
Fontaine frolics in a festival with the...
Fontaine has finally overcome a fairly turbulent time and it's time to get back to the important things in Genshin Impact. Version 4.3, Roses and Muskets, will kick off December 20th and bring Travelers to one of the nation's most important events... | Read more »
TouchArcade Game of the Week: ‘Sonic Dre...
I can still remember the time I played my first 3D Sonic game. It was at Hollywood Video (that’s a video rental store for you young ones out there) and my buddy was the manager, and he invited me and my friend to hang out in the store after they... | Read more »
SwitchArcade Round-Up: Strictly Limited...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for December 8th, 2023. In today’s article, we start off with a couple of news items. Nothing from The Game Awards, that’s a bit beyond the scope of what I usually do here. But I do have... | Read more »
Football Manager 2024 Interview – We Tal...
Last month, SEGA and Sports Interactive released Football Manager 2024 on Apple Arcade (Touch), Netflix (Mobile), consoles, PC, and even Game Pass. If you missed my detailed review covering many versions of the game, read it here. | Read more »
‘Shiren the Wanderer: The Mystery Dungeo...
Recently, my son and I were invited to attend a special hands-on preview event at Spike Chunsoft’s headquarters in Tokyo to play the upcoming Shiren the Wanderer: The Mystery Dungeon of Serpentcoil Island for Nintendo Switch, which is scheduled for... | Read more »
Apple Arcade Weekly Round-Up: Updates fo...
We just had a huge content drop on Apple Arcade earlier this week with Sonic Dream Team, Disney Dreamlight Valley, Puzzles and Dragons, and more hitting the service. Today (and as of a few days ago), many notable games on the service have gotten... | Read more »
‘Genshin Impact’ Version 4.3 Update “Ros...
Following two trailers during The Game Awards 2023, HoYoverse has more news today with the next major Genshin Impact (Free) update detailed for all platforms. | Read more »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs are on Holiday sale f...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs in stock and back on Holiday sale for $150-$200 off MSRP in Space Gray, Silver, Starlight, and Midnight colors. Their prices are among the lowest... Read more
15-inch M2 MacBook Airs are back on Holiday s...
Apple retailers have 15-inch M2 MacBook Air back on Holiday sale for $250 off MSRP. Here is where to find the cheapest 15″ Air today: (1): Apple 15-inch MacBook Airs with M2 CPUs are in stock and on... Read more
Update: Apple Watch Series 9 models now $70 o...
Walmart has Apple Watch Series 9 models on Holiday sale for $70 off MSRP on their online store this weekend (that’s $20 cheaper than their earlier price). Sale prices available for online orders only... Read more
Apple’s AirTags 4-Pack is on Holiday sale for...
Apple retailers have 4-pack AirTags on sale this weekend for $19 off MSRP as part of their Holiday sales. These make a great stocking stuffer: (1): Amazon has Apple AirTags 4 Pack on sale for $79.99... Read more
Sunday Sale: $100 off every Apple iPad mini 6
Amazon is offering Apple’s 8.3″ iPad minis for $100 off MSRP, including free shipping, as part of their Holiday sale this weekend. Prices start at $399. Amazon’s prices are the lowest currently... Read more
16-inch M3 Pro MacBook Pros (18GB/512GB) are...
Looking for the best price on a 16″ M3 Pro MacBook Pro this Holiday shopping season? B&H and Amazon are currently offering a $250 discount on the 16″ M3 Pro MacBook Pro (18GB RAM/512GB SSD),... Read more
Apple Watch SE models on Holiday sale for $50...
Walmart has Apple Watch SE GPS-only models on Holiday sale on their online store for $50 off MSRP this weekend. Sale prices for online orders only, in-store prices may vary. Order online, and choose... Read more
Apple Watch Series 9 models on Holiday sale t...
Walmart has Apple Watch Series 9 models on Holiday sale for $50 off MSRP on their online store this weekend. Sale prices available for online orders only, in-store prices may vary. Order online, and... Read more
Apple has the 13-inch M2 MacBook Air in stock...
Apple has Certified Refurbished 13″ M2 MacBook Airs available starting at only $929 and ranging up to $210 off MSRP. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year... Read more
Apple’s 10th-generation iPads on Holiday sale...
Amazon has Apple’s 10th-generation WiFi iPads on sale for $100 off MSRP, starting at only $349, as part of their Holiday sales this weekend. With the discount, Amazon’s prices are the lowest we’ve... Read more

Jobs Board

Principal Offering Sales - Modern Workplace...
…Job Description **Who you are** + **Drives Modern Workplace sale, focusing on Apple Managed Services across the enterprise globally.** + **Owns the Apple Read more
Material Handler 1 - *Apple* (1st shift) -...
Material Handler 1 - Apple (1st shift)Apply now " Apply now + Start apply with LinkedIn + Apply Now Start + Please wait Date:Dec 8, 2023 Location: Irwindale, CA, US, Read more
Macintosh/ *Apple* Systems Administrator, TS...
…to a team-based environment. + Perform systems administration support tasks for Apple MacOS and iOS operating systems. + TDY travel (approximately 25%) for Read more
Principal Offering Sales - Modern Workplace...
…Job Description **Who you are** + **Drives Modern Workplace sale, focusing on Apple Managed Services across the enterprise globally.** + **Owns the Apple Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.