Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Chapter 18. Organizing Your Code with Ha... > Tips for Designing and Using Handler... - Pg. 526

526 CHAPTER 18: Organizing Your Code with Handlers Using User-Defined Handlers from Other Scripts Another cool thing about stay-open scripts is that you can call their handlers from an outside script while they are running. In fact, the process of sending a command to a stay-open applet is no different from sending a command to a regular scriptable application, although the applet's handler names will usually be AppleScript identifiers rather than dictionary-defined keywords. Let's try this now. First, save Script 18­18 as a stay-open applet named My Clock. Script 18­18. on tell_time() display dialog (time string of (current date)) end tell Next, create a new AppleScript Editor document and type in the code shown in Script 18­19. Script 18­19. tell application "My Clock" activate tell_time() end tell When you run this script, it sends an activate command to the My Clock applet, causing it to come to the front. This is followed by a tell_time command, which causes the applet to execute its tell_time handler, displaying the current time to the user. Tips for Designing and Using Handlers The following few sections contain tips for creating and using handlers. Handlers can be a boon for efficient script writing, and with the right organization, you will be able to spend more time on the function of the script and less time on messing with syntax. Organizing Code One of the brilliant factors handlers add to your scripts is organization. They allow you to tell the story of your script in your language, rather than in a programming language. You know those people who tell a story about something they did but feel compelled to go into every last detail, until you lose the whole story? Well, without handlers, AppleScript can be like that too. As you read through a script and try to understand it, you don't want to be bothered with the 50 lines of script that made a certain function of the script work. What you want is to quickly get a general idea of the script's organization, what happens in what order, and the basic branching that makes up the script. For instance, a medium-sized script might contain several dozen conditional blocks and repeat loops, out of which only a few actually play a key role in the overall structure of the script. These statements should be included in the main run handler, making it obvious that they are in overall charge of the script's execution. Less important