This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Fl Using Components Mx as PDF for free.
Trademarks Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware, Authorware Star, Backstage, Bright Tiger, Clustercats, ColdFusion, Contribute, Design In Motion, Director, Dream Templates, Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, Flash Lite, Flex, Fontographer, FreeHand, Generator, HomeSite, JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track, LikeMinds, Lingo, Live Effects, MacRecorder Logo and Design, Macromedia, Macromedia Action!, Macromedia Breeze, Macromedia Flash, Macromedia M Logo and Design, Macromedia Spectra, Macromedia xRes Logo and Design, MacroModel, Made with Macromedia, Made with Macromedia Logo and Design, MAGIC Logo and Design, Mediamaker, Movie Critic, Open Sesame!, Roundtrip, Roundtrip HTML, Shockwave, Sitespring, SoundEdit, Titlemaker, UltraDev, Web Design 101, what the web can be, and Xtra are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally. Third-Party Information This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites. Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com). Sorenson™ Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 are the professional standard authoring tools for producing high-impact web experiences. Components are the building blocks for the Rich Internet Applications that provide those experiences. A component is a movie clip with parameters that are set during authoring in Macromedia Flash, and with ActionScript methods, properties, and events that allow you to customize the component at runtime. Components are designed to allow developers to reuse and share code, and to encapsulate complex functionality that designers can use and customize without using ActionScript. Components are built on version 2 of the Macromedia Component Architecture, which allows you to easily and quickly build robust applications with a consistent appearance and behavior. This book describes how to build applications with version 2 components and describes each component’s application programming interface (API). It includes usage scenarios and procedural samples for using the Flash MX 2004 or Flash MX Professional 2004 version 2 components, as well as descriptions of the component APIs, in alphabetical order. You can use components created by Macromedia, download components created by other developers, or create your own components. This chapter contains the following sections: Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 System requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Typographical conventions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Terms used in this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Additional resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Intended audience This book is for developers who are building Flash MX 2004 or Flash MX Professional 2004 applications and want to use components to speed development. You should already be familiar with developing applications in Flash and writing ActionScript.
7
If you are less experienced with writing ActionScript, you can add components to a document, set their parameters in the Property inspector or Component inspector, and use the Behaviors panel to handle their events. For example, you could attach a Go To Web Page behavior to a Button component that opens a URL in a web browser when the button is clicked without writing any ActionScript code. If you are a programmer who wants to create more robust applications, you can create components dynamically, use ActionScript to set properties and call methods at runtime, and use the listener event model to handle events. For more information, see Chapter 3, “Working with Components,” on page 43.
System requirements Macromedia components do not have any system requirements in addition to Flash MX 2004 or Flash MX Professional 2004. Any SWF file that uses version 2 components must be viewed with Flash Player 6 (6.0.79.0) or later.
About the documentation This document explains the details of using components to develop Flash applications. It assumes that you have general knowledge of Macromedia Flash and ActionScript. Specific documentation about Flash and related products is available separately. This document is available as a PDF file and as online help. To view the online help, start Flash and select Help > Using Components. For information about Macromedia Flash, see the following documents:
• • • •
Getting Started with Flash (or Getting Started Help) Using Flash (or Using Flash Help) Using ActionScript in Flash (or Using ActionScript Help) Flash ActionScript Language Reference (or Flash ActionScript Language Reference Help)
Typographical conventions The following typographical conventions are used in this book:
• Italic font indicates a value that should be replaced (for example, in a folder path). • Code font indicates ActionScript code. • Code font italic indicates a code item that should be replaced (for example, an ActionScript parameter).
• Bold font indicates a value that you enter. Note: Bold font is not the same as the font used for run-in headings. Run-in heading font is used as an alternative to a bullet.
8
Introduction: Getting Started with Components
Terms used in this manual The following terms are used in this manual: at runtime
When the code is running in Flash Player.
while authoring
While you are working in the Flash authoring environment.
Additional resources For the latest information on Flash, plus advice from expert users, advanced topics, examples, tips, and other updates, see the Macromedia DevNet website at www.macromedia.com/devnet, which is updated regularly. Check the website often for the latest news on Flash and how to get the most out of the program. For TechNotes, documentation updates, and links to additional resources in the Flash Community, see the Macromedia Flash Support Center at www.macromedia.com/support/flash. For detailed information on ActionScript terms, syntax, and usage, see Using ActionScript in Flash and Flash ActionScript Language Reference. For an introduction to using components, see the Macromedia On Demand Seminar, Flash MX 2004 Family: Using UI Components at www.macromedia.com/macromedia/events/online/ ondemand/index.html.
Additional resources
9
10
Introduction: Getting Started with Components
CHAPTER 1 About Components
Components are movie clips with parameters that allow you to modify their appearance and behavior. A component can be a simple user interface control, such as a radio button or a check box, or it can contain content, such as a scroll pane; a component can also be non-visual, like the FocusManager that allows you to control which object receives focus in an application. Components enable anyone to build complex Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 applications, even if they don’t have an advanced understanding of ActionScript. Rather than creating custom buttons, combo boxes, and lists, you can drag these components from the Components panel to add functionality to your applications. You can also easily customize the look and feel of components to suit your design needs. Components are built on version 2 of the Macromedia Component Architecture, which allows you to easily and quickly build robust applications with a consistent appearance and behavior. The version 2 architecture includes classes on which all components are based, styles and skins mechanisms that allow you to customize component appearance, a broadcaster/listener event model, depth and focus management, accessibility implementation, and more. Each component has predefined parameters that you can set while authoring in Flash. Each component also has a unique set of ActionScript methods, properties, and events, also called an API (application programming interface), that allows you to set parameters and additional options at runtime. Flash MX 2004 and Flash MX Professional 2004 include many new Flash components and several new versions of components that were included in Flash MX. For a complete list of components included with Flash MX 2004 and Flash MX Professional 2004, see “Installing components” on page 12. You can also download components built by members of the Flash community at the Macromedia Exchange at www.macromedia.com/cfusion/exchange/index.cfm. This chapter contains the following sections: Installing components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Where component files are stored . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Benefits of using components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Categories of components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Installing components A set of Macromedia components is already installed when you launch Flash MX 2004 or Flash MX Professional 2004 for the first time. You can view them in the Components panel. Flash MX 2004 includes the following components:
Flash MX Professional 2004 includes the Flash MX 2004 components and the following additional components and classes:
• • • • • • • • • • • •
12
Accordion component (Flash Professional only) Alert component (Flash Professional only) Data binding classes (Flash Professional only) DateField component (Flash Professional only) DataGrid component (Flash Professional only) DataHolder component (Flash Professional only) DataSet component (Flash Professional only) DateChooser component (Flash Professional only) Form class (Flash Professional only) Media components (Flash Professional only) Menu component (Flash Professional only) MenuBar component (Flash Professional only)
Chapter 1: About Components
• • • • • • •
RDBMSResolver component (Flash Professional only) Screen class (Flash Professional only) Slide class (Flash Professional only) Tree component (Flash Professional only) WebServiceConnector class (Flash Professional only) XMLConnector component (Flash Professional only) XUpdateResolver component (Flash Professional only)
To verify installation of the Flash MX 2004 or Flash MX Professional 2004 components:
1. Start Flash. 2. Select Window > Development Panels > Components to open the Components panel if it isn’t
already open. 3. Select UI Components to expand the tree and view the installed components.
You can also download components from the Macromedia Exchange at www.macromedia.com/ exchange. To install components downloaded from the Exchange, download and install the Macromedia Extension Manager at www.macromedia.com/exchange/em_download/ Any component can appear in the Components panel in Flash. Follow these steps to install components on either a Windows or Macintosh computer. To install components on a Windows-based or a Macintosh computer:
1. Quit Flash. 2. Place the SWC or FLA file containing the component in the following folder on your hard disk: ■
3. Open Flash. 4. Select Window > Development Panels > Components to view the component in the
Components panel if it isn’t already open.
Where component files are stored Flash components are stored in the application-level Configuration folder. Note: For information about these folders, see “Configuration folders installed with Flash” in Using Flash.
Components are installed in the following locations:
• Windows 2000 or Windows XP: C:\Program Files\Macromedia\Flash MX 2004\language\Configuration\Components
• Mac OS X: HD/Applications/Macromedia Flash MX 2004/Configuration/Components The source ActionScript files for components are located in the mx subfolder of the First Run folder.
Where component files are stored
13
If you’ve added components, you’ll need to refresh the Components panel. To refresh the contents of the Components panel:
• Select Reload from the Components panel menu.
To remove a component from the Components panel:
• Remove the MXP or FLA file from the Configuration folder. Benefits of using components Components enable the separation of coding and design. They also allow you to reuse code, either in components you create, or by downloading and installing components created by other developers. Components allow coders to create functionality that designers can use in applications. Developers can encapsulate frequently used functionality into components and designers can customize the look and behavior of components by changing parameters in the Property inspector or the Component inspector. Members of the Flash community can use the Macromedia Exchange at www.macromedia.com/ go/exchange to exchange components. By using components, you no longer need to build each element in a complex web application from scratch. You can find the components you need and put them together in a Flash document to create a new application. Components that are based on the version 2 architecture share core functionality such as styles, event handling, skinning, focus management, and depth management. When you add the first version 2 component to an application, there is approximately 25K added to the document that provides this core functionality. When you add additional components, that same 25K is reused for them as well, resulting in a smaller increase in size to your document than you may expect. For information about upgrading components, see “Upgrading version 1 components to version 2 architecture” on page 53.
14
Chapter 1: About Components
Categories of components Components included with Flash MX 2004 and Flash MX Professional 2004 fall into the following five categories (the locations of their ActionScript source files roughly correspond to these categories as well and are listed in parentheses):
• User interface components (mx.controls.*) User interface components allow you to interact with an application; for example, the RadioButton, CheckBox, and TextInput components are user interface controls.
• Data components (mx.data.*) Data components allow you to load and manipulate information from data sources; the WebServiceConnector and XMLConnector components are data components. Note: The source files for the data components aren’t installed with Flash. However, some of the supporting ActionScript files are installed.
• Media components (mx.controls.*) Media components let you play back and control streaming media; MediaController, MediaPlayback, and MediaDisplay are media components.
• Managers (mx.managers.*) Managers are nonvisual components that allow you to manage a feature, such as focus or depth, in an application; the FocusManager, DepthManager, PopUpManager, StyleManager, and SystemManager components are manager components.
• Screens (mx.screens.*) The screens category includes the ActionScript classes that allow you to control forms and slides in Flash MX Professional 2004. For a complete list of each category, see Chapter 6, “Components Dictionary,” on page 91.
About version 2 component architecture You can use the Property inspector or the Component inspector to change component parameters to make use of the basic functionality of components. However, if you want greater control over components, you need to use their APIs and understand a little bit about the way they were built. Flash MX 2004 and Flash MX Professional 2004 components are built with version 2 of the Macromedia Component Architecture. Version 2 components are supported by Flash Player 6.79 and Flash Player 7. These components are not always compatible with components built using version 1 architecture (all components released before Flash MX 2004). Also, the original version 1 components are not supported by Flash Player 7. For more information, see “Upgrading version 1 components to version 2 architecture” on page 53. Note: Flash MX UI components have been updated to work with Flash Player 7. These updated components are still based on version 1 architecture. You can download them from the Macromedia Flash Exchange at www.macromedia.com/cfusion/exchange/ index.cfm#loc=en_us&view=sn106&viewName=Exchange%20Search%20Details&authorid=606 39501&page=0&scrollPos=0&subcatid=0&snid=sn106&itemnumber=0&extid=1009423&catid=0.
About version 2 component architecture
15
Version 2 components are included in the Components panel as compiled clip (SWC) symbols. A compiled clip is a component movie clip whose code has been compiled. Compiled clips cannot be edited, but you can change their parameters in the Property inspector and Component inspector, just as you would with any component. For more information, see “About compiled clips and SWC files” on page 17. Version 2 components are written in ActionScript 2.0. Each component is a class and each class is in an ActionScript package. For example, a radio button component is an instance of the RadioButton class whose package name is mx.controls. For more information about packages, see “Using packages” in Using ActionScript in Flash. Most UI components built with version 2 of the Macromedia Component Architecture are subclasses of the UIObject and UIComponent classes and inherit all properties, methods, and events from those classes. Many components are also subclasses of other components. The inheritance path of each component is indicated in its entry in Chapter 6, “Components Dictionary,” on page 91. Note: The class hierarchy is also available as a GIF file (v2_Flash_component_arch.gif) in the Examples folder.
All components also use the same event model, CSS-based styles, and built-in themes and skinning mechanisms. For more information on styles and skinning, see Chapter 5, “Customizing Components,” on page 67. For more information on event handling, see Chapter 3, “Working with Components,” on page 43. For a detailed explanation of the version 2 component architecture, see Chapter 7, “Creating Components,” on page 915.
What’s new in version 2 components This section outlines the differences between version 1 and version 2 components from the perspective of a developer using components to build Flash applications. For detailed information about the differences between the version 1 and version 2 architectures for building components, see Chapter 7, “Creating Components,” on page 915. The Component inspector allows you to change component parameters while authoring in Macromedia Flash and Macromedia Dreamweaver. (See “Setting component parameters” on page 47.) The listener event model
allows listeners to handle events. (See Chapter 4, “Handling Component Events,” on page 55.) There isn’t a clickHandler parameter in the Property inspector, as there was in Flash MX; you must write ActionScript code to handle events.
Skin properties let you load individual skins (for example, up and down arrows or the check for a check box) at runtime. (See “About skinning components” on page 80.) CSS-based styles allow you to create a consistent look and feel across applications. (See “Using styles to customize component color and text” on page 67.) To set a component style, use the following syntax: componentInstance.setStyle("styleName", value). Themes allow you to drag a new look from the library onto a set of components. (See “About themes” on page 77.)
16
Chapter 1: About Components
The Halo theme provides a ready-made, responsive, and flexible user interface for applications. Halo is the default theme that the version 2 components use. (See “About themes” on page 77.) Manager classes provide an easy way to handle focus and depth in a application. (See “Creating custom focus navigation” on page 50 and “Managing component depth in a document” on page 51.) The base classes UIObject and UIComponent provide core methods, properties, and events to components that extend them. (See “UIComponent class” on page 793 and “UIObject class” on page 808.) Packaging as a SWC file
allows easy distribution and concealable code. See Chapter 7, “Creating Components,” on page 915.
Built-in data binding
is available through the Component inspector. For more information, see Using Flash > Data Integration.
An easily extendable class hierarchy
using ActionScript 2.0 allows you to create unique namespaces, import classes as needed, and subclass easily to extend components. See Chapter 7, “Creating Components,” on page 915 and Flash ActionScript Language Reference.
About compiled clips and SWC files Components included with Flash MX 2004 or Flash MX Professional 2004 are not FLA files— they are compiled clips that have been packaged into SWC files. SWC is the Macromedia file format for distributing components; it contains a compiled clip, the component’s ActionScript class file, and other files that describe the component. For details about SWC files, see “Exporting and distributing a component” on page 953. When you place a SWC file in the First Run/Components folder, the component appears in the Components panel. When you add a component to the Stage from the Components panel, a compiled clip symbol is added to the library. A compiled clip is a package of precompiled symbols and ActionScript. It’s used to avoid recompiling symbols and code that aren’t going to change. A movie clip can also be “compiled” in Flash and converted to a compiled clip symbol. For example, a movie clip with a lot of ActionScript code that doesn’t change often could be turned into a compiled clip. The compiled clip symbol behaves just like the movie clip symbol from which it was compiled, but compiled clips appear and publish much faster than regular movie clip symbols. Compiled clips can’t be edited, but they do have properties that appear in the Property inspector and the Component inspector. To compile a movie clip symbol:
• Right-click (Windows) or Control-click (Macintosh) the movie clip in the Library panel, and then select Convert to Compiled Clip. To export a SWC file:
• Select the movie clip in the Library panel and right-click (Windows) or Control-click (Macintosh), and then select Export SWC File. Note: Flash MX 2004 and Flash MX Professional 2004 continue to support FLA components.
About compiled clips and SWC files
17
Accessibility and components A growing requirement for web content is that it should be accessible; that is, usable for people with a variety of disabilities. Visual content in Flash applications can be made accessible to the visually impaired with the use of screen reader software, which provides a spoken audio description of the contents of the screen. When a component is created, the author can write ActionScript that enables communication between the component and a screen reader. Then, when a developer uses components to build an application in Flash, the developer uses the Accessibility panel to configure each component instance. Most components built by Macromedia are designed for accessibility. To find out whether a component is accessible, see its entry in Chapter 6, “Components Dictionary,” on page 91. When you’re building an application in Flash, you’ll need to add one line of code for each component (mx.accessibility.ComponentNameAccImpl.enableAccessibility();), and set the accessibility parameters in the Accessibility panel. Accessibility for components works the same way as it works for all Flash movie clips. Most components built by Macromedia are also navigable by the keyboard. Each component’s entry in Chapter 6, “Components Dictionary,” indicates whether or not you can control the component with the keyboard.
18
Chapter 1: About Components
CHAPTER 2 Creating an Application with Components (Flash Professional Only)
Components in Flash are prebuilt elements that you can use when creating Flash applications, to add user interface controls, data connectivity, and other functionality. Components can save you work when you’re building an application, because you don’t have to create all the design and functionality from scratch. This tutorial shows how to build a Flash application using components available in Macromedia Flash MX Professional 2004, including a variety of user interface and data connectivity components. You’ll learn how to work with components by using panels and other interface features in the Flash authoring environment and by using ActionScript.
About working with components All components are listed in the Components panel. To use a component, you add an instance of the component to a Flash application. You can add a component instance in several ways:
• To add a component instance to an application while authoring, drag the component from the Components panel onto the Stage. This also places the component in the library. You can add additional instances of the component by dragging the component from the library onto the Stage. For more information, see “The Components panel” on page 44 and “Adding components during authoring” on page 44.
• To create a component instance dynamically, first add the component to the library: drag the component from the Components panel onto the Stage and then delete the instance on the Stage (the component remains in the library). Then add ActionScript to the application to create the instance, as you would create an instance of a movie clip or other object in the library. For more information on adding components dynamically, see “Adding components at runtime with ActionScript” on page 46. Once the component is added to the library, you can create instances either by dragging to the Stage or by writing ActionScript.
19
You can modify the appearance and behavior of components by setting component parameters in the authoring environment, using the Parameters tab in either the Property inspector or the Component inspector. You can also control components during runtime using ActionScript. All components have ActionScript methods, properties, and events. For more information on authoring parameters, see “Setting component parameters” on page 47. After you build an application using components, you can update or repurpose it simply by resetting component parameters, without having to rewrite code. An application built with components can even be updated by someone who doesn’t know all the code used to create it. The components included with Flash MX 2004 and Flash MX Professional 2004 are SWC files (the Macromedia file format for components). A SWC file contains a compiled clip of the component, as well as an icon that appears in the Components panel, and other assets to create component functionality. Compiled clips are complex symbols that are precompiled so that they are easier to work with in a Flash document. For example, both the Test Movie and the Publish procedures run faster with compiled clips, because the clips don’t need to compile when the SWF file is generated. Because components are precompiled, you cannot edit them as you would uncompiled movie clips (FLA files). You modify components by setting their parameters or by using their ActionScript methods, properties, and events. For more general information about components, see the following topics:
• Chapter 1, “About Components” • Chapter 3, “Working with Components” • Chapter 6, “Components Dictionary” About this tutorial This tutorial is intended for intermediate Flash users who are familiar with the Flash authoring environment and have some experience with ActionScript. In the authoring environment, you should have some experience using panels, tools, the Timeline, and the library. In ActionScript, you should be familiar with writing functions, adding event listeners, and using class files.
• Build the application architecture: Add component instances and movie clips to build the application interface. This section covers adding UI and data components and setting their parameters while authoring.
• Bind components to display product information from an external source: Bind components to one another to distribute and display data from an external XML file. This section covers using the data integration features in the Flash authoring environment to bind data and UI components together.
• Add ActionScript to the main Timeline: Add ActionScript code to create interactive functionality. This section includes importing the classes for the components used in the application. Most of the code places event listeners on components to process data in response to user input.
20
Chapter 2: Creating an Application with Components (Flash Professional Only)
If you are experienced with building application architecture in Flash, you may want to skip the first section of the tutorial and read the second and third sections while referring to the finished FLA file of the sample application, to learn about the procedures used to bind the components and add event listeners for data integration. (To view the finished FLA file, see the next section.) All the ActionScript needed for creating the sample application is provided with this tutorial. However, to understand the scripting concepts and create your own application using the procedures described here, you should have some prior experience writing ActionScript.
View the application In this tutorial you’ll create an application for the “Fix Your Mistake” gift service, which helps users select an appropriate gift when they need to make amends with someone. Keep in mind that the sample application is for demonstration purposes only. It is not possible to check errors or verify data in the sample. The sample application uses several UI components (including the ComboBox, TextArea, and Button components) to create the application interface. It includes data components to connect to external data sources: the XMLConnector component (to connect to an XML file) and the DataSet component (to filter the data from the XML file and make the data available to UI components). The application also uses the WebService class to connect dynamically to a web service. View the SWF file for the completed application To view the completed application, open the first_app_v3.swf file at the following location:
• In Windows: boot drive\Program Files\Macromedia\Flash MX 2004\Samples\ HelpExamples\components_application
• On the Macintosh: Macintosh HD/Applications/Macromedia Flash MX 2004/Samples/ HelpExamples/components_application To see how the application works, first click the arrow control in the What Did You Do? section. Select from a list of blunders you might have committed (ranging in severity from Forgot to Water Your Plants to Burned Your House Down). This section uses the ComboBox UI component, populated by a web service. A list of gift suggestions appears in the Gift Ideas section. Click a gift to view more information about it. In the pop-up window that appears, select the quantity you want using the numeric stepper, and click Add to Cart. Click the close box to close the window. Back in the main screen of the application, click Checkout. This section uses the XMLConnector data component to connect to an external XML file, the DataSet data component to filter the data from the XML file, and the DataGrid UI component to display the data.
View the application
21
On the Checkout screen, click the Billing Information, Shipping Information, and Credit Card Information headers to view the form fields for each of these items. To place an order, you can add the appropriate information in each of these panes, and click Confirm at the bottom of the Credit Card Information pane. You can also click Back to return to the main screen. Close the SWF file when you finish examining the completed application. This screen includes several UI components (Accordion, TextArea, and others) to display information and provide fields for user input. View the FLA file for the completed application To view the FLA file for the application, open the first_app_v3.fla file in the components_application folder (the same folder that contains the first_app_v3.swf file). Examine the Stage, library, and Actions panel to see the content for the application. Notice that all the components used in the application appear in the library (along with graphics files and other assets used to create the application architecture). Drag the playhead to view the keyframes labeled Home (Frame 1) and Checkout (Frame 10). Some components appear as instances on the Stage. Some are referenced in the ActionScript code but do not appear until runtime.
About data integration in the sample application The sample application uses features of the Flash data integration architecture to connect to external data sources, manage the data from those sources, and map the data to UI components in the application for display. The Flash data integration architecture enables you to work with external data in different ways, using components and ActionScript classes. For general information on Flash data integration features, see Chapter 14, “Data Integration (Flash Professional Only)” in Using Flash. The sample application uses both components and classes, to introduce you to different ways of working with data:
• The XMLConnector component connects to an external XML file. Using this component is similar to loading an external XML file with XML.load() (the load method of the XML object). However, the XMLConnector component is far more powerful and versatile, because the component makes the XML data available for display in a variety of UI components, simply by binding component parameters in the Flash authoring environment. For more information, see “XMLConnector component (Flash Professional only)” on page 894.
• The DataSet component manages and filters data from the XML file. You bind the XMLConnector component to the DataSet component in the Flash authoring environment, and then bind the DataSet component to a UI component. For more information, see “DataSet component (Flash Professional only)” on page 301.
• The DataGrid component displays data from the XML file that has been filtered by the DataSet. You bind the DataSet component to the DataGrid component. (You can also bind the DataSet component to other UI components. The DataGrid component is just one example.) For more information, see “DataGrid component (Flash Professional only)” on page 247.
22
Chapter 2: Creating an Application with Components (Flash Professional Only)
• The WebService class is part of a set of web service classes, which provides a set of methods, events, and properties that enable you to connect to a web service. The WebService class is different from the WebServiceConnector component. (The WebServiceConnector component, like the XMLConnector component, enables you to connect to an external data source—in this case, a web service—by adding a component to an application and setting its parameters.) The sample application uses the WebService class rather than the WebServiceConnector component simply to demonstrate another way of connecting to an external data source. For more information on the set of web service classes, see “Web service classes (Flash Professional only)” on page 842.
Build the application architecture To build the application architecture, you’ll add components to the Stage on Frame 1 (for the main screen) and Frame 10 (for the Checkout screen). You’ll also create movie clips that will be used to display information inside various components. Add component instances for the main screen of the application You’ll start the application by adding instances of the ComboBox, DataGrid, DataSet, XMLConnector, and Button components to the Stage. You’ll also add the Window component to the library. Later in the tutorial you’ll add code to create instances of the Window component dynamically, to display product information when a user clicks an item in the Gift Ideas section. The ComboBox instance will display the list of blunders that the user can choose from. The list will be provided by a web service that you’ll connect to the ComboBox component later in the tutorial, using the WebService class. The DataGrid instance will display the list of gift ideas that the user can choose from. The list of gifts (and all the product details for each gift) will be provided by an external XML file, which you connect to by means of the XMLConnector component. To filter and sort the data from the XML file, you’ll use the DataSet component. Later in the tutorial, you’ll use the Flash data binding features to bind the DataGrid, XMLConnector, and DataSet components to interpret and display product information from the XML file. The Window component will be used to create a pop-up window that displays information on each product in the Gift Ideas list. 1. Open the first_app_v3_start.fla file for the application, located in the components_application
folder (the same folder that contains the first_app_v3.swf and first_app_v3.fla files). The start_app.fla file contains three layers: a Background layer with a black background image and text titles, a Text layer with text labels for sections of the application, and a Labels layer with labels on the first frame (Home) and the tenth frame (Checkout). 2. Select File > Save As. Rename the file and save it to your hard drive. 3. In the Timeline, select the Labels layer and click the Add Layer button to add a new layer above
it. Name the new layer Form. You’ll place the component instances on this layer.
Build the application architecture
23
4. Make sure the Form layer is selected. In the Components panel (Window > Development
Panels > Components), locate the ComboBox component in the UI Components folder. Drag an instance of ComboBox onto the Stage. Place it below the What Did You Do? text. In the Property inspector (Window > Properties), for the instance name enter problems_cb. Set Width to 400 pixels. Notice that the ComboBox component symbol is added to the library (Window > Library). When you drag an instance of a component to the Stage, the compiled clip symbol for the component is added to the library. As with all symbols in Flash, you can create additional instances of the component by dragging the library symbol onto the Stage. 5. Drag an instance of the DataGrid component from the UI Components folder in the
Components panel onto the Stage. Place it below the Gift Ideas text. Enter products_dg for the instance name. Set Width to 400 pixels and Height to 160 pixels. 6. Drag an instance of the DataSet component from the Data Components folder in the
Components panel onto the side of the Stage. (The DataSet component does not appear in the application at runtime. The DataSet icon is simply a placeholder that you work with in the Flash authoring environment.) Enter products_ds for the instance name. 7. Drag an instance of the XMLConnector component from the Data Components folder in the
Components panel to the side of the Stage. (Like the DataSet component, the XMLConnector component does not appear in the application at runtime.) Enter products_xmlcon for the instance name. Click the Parameters tab in the Property inspector, and enter http://www.flashmx.com/mm/firstapp/products.xml for the URL property. Note: You can also use the Component inspector (Window > Development Panels > Component Inspector) to set parameters for components. The Parameters tab in the Property inspector and the Component inspector work in the same way.
The URL specifies an external XML file with data about the products that appear in the Gift Ideas section of the application. Later in the tutorial you’ll use data binding to bind the XMLConnector, DataSet, and DataGrid components together; the DataSet component will filter data from the external XML file, and the DataGrid component will display it. 8. Drag an instance of the Button component from the UI Components folder in the Components
panel onto the Stage. Place it in the lower right corner of the Stage. Enter checkout_button for the instance name. Click the Parameters tab and enter Checkout for the label property. 9. Drag an instance of the Window component from the UI Components folder in the
Components panel onto the Stage. Select the instance on the Stage and delete it. The Window component symbol is now added to the library. Later in the tutorial, you’ll create instances of the Window component using ActionScript. Remember to save your work frequently.
24
Chapter 2: Creating an Application with Components (Flash Professional Only)
Create a movie clip with component instances to display product details In the application, a pop-up window appears when a user clicks on a product in the Gift Ideas section. The pop-up window contains component instances that display information for the product, including a text description, image, and price. To make this pop-up window, you’ll create a movie clip symbol and add instances of the Loader, TextArea, Label, NumericStepper, and Button components. Later in the tutorial, you’ll add ActionScript that dynamically creates an instance of this movie clip for each product. These movie clip instances will be displayed in the Window component, which you added to the library earlier. The component instances will be populated with elements from the external XML file. 1. In the Library panel (Window > Library), click the options menu on the right side of the title
bar and select New Symbol. 2. In the Create New Symbol dialog box, enter ProductForm for Name and select Movie Clip for
Behavior. 3. Click the Advanced button. Under Linkage, select Export for ActionScript, leave Export in First
Frame selected, and click OK. A document window for the new symbol opens in symbolediting mode. For movie clip symbols that are in the library but not on the Stage, you must select Export for ActionScript so that you can manipulate them using ActionScript. (Exporting in first frame means that the movie clip is available as soon as the first frame loads.) Later in the tutorial you’ll add ActionScript that will generate an instance of the movie clip dynamically each time a user clicks a product in the Gift Ideas section. 4. In the Timeline for the new symbol, select Layer 1 and rename it Components. 5. Drag an instance of the Loader component from the UI Components folder in the Components
panel onto the Stage. Set the X, Y coordinates to 5, 5. Enter image_ldr for the instance name. Click the Parameters tab in the Property inspector. Select false for autoLoad and false for scaleContent. The Loader component instance will be used to display an image of the product. The false setting for autoLoad specifies that the image will not load automatically. The false setting for scaleContent specifies that the image will not be scaled. Later in the tutorial you’ll add code that loads the image dynamically, based on the product that the user selects in the Gift Ideas section. 6. Drag an instance of the TextArea component from the UI Components folder in the
Components panel onto the Stage. Place it next to the Loader component. Set the X, Y coordinates to 125, 5. Enter description_ta for the instance name. Click the Parameters tab in the Property inspector. For editable, select false. For html, select true. For wordWrap, select true. The TextArea component instance will be used to display a text description of the selected product. The selected settings specify that the text cannot be edited by a user, that it can be formatted with HMTL tags, and that lines will wrap to fit the size of the text area.
Build the application architecture
25
7. Drag an instance of the Label component from the UI Components folder in the Components
panel onto the Stage. Place it below the Loader component. Set the X, Y coordinates to 5, 145. Enter price_lbl for the instance name. Click the Parameters tab in the Property inspector. For autoSize, select left. For html, select true. The Label component instance will display the price of the product and the price qualifier (the quantity of products indicated by the specified price, such as “each” or “one dozen.”) 8. Drag an instance of the NumericStepper component from the UI Components folder in the
Components panel onto the Stage. Place it below the TextArea component. Set the X, Y coordinates to 135, 145. Enter quantity_ns for the instance name. Click the Parameters tab in the Property inspector. For minimum, enter 1. Setting minimum to 1 specifies that the user must select at least one of the product in order to add the item to the cart. 9. Drag an instance of the Button component from the UI Components folder in the Components
panel onto the Stage. Place it beside the NumericStepper component. Set the X, Y coordinates to 225, 145. Enter addToCart_button for the instance name. Click the Parameters tab in the Property inspector. For label, enter Add To Cart. Add code to the ProductForm movie clip Next, you’ll add ActionScript to the ProductForm movie clip that you just created. The ActionScript populates the components in the movie clip with information about the selected product, and adds an event listener to the Add to Cart button that adds the selected product to the cart. For more information on working with event listeners, see “Using event listeners” in Using ActionScript in Flash. 1. In the Timeline of the ProductForm movie clip, create a new layer and name it Actions. Select
the first frame in the Actions layer. 2. In the Actions panel, add the following code: // create an object to reference the selected product item in the DataGrid var thisProduct:Object = this._parent._parent.products_dg.selectedItem; // populate the description_ta TextArea and price_lbl Label instances with // data from the selected product description_ta.text = thisProduct.description; price_lbl.text = "$"+thisProduct.price+" "+thisProduct.priceQualifier+""; // load an image of the product from the application directory image_ldr.load(thisProduct.image); Note: The code includes comments explaining its purpose. It’s a good idea to include comments like these in all the ActionScript code you write, so that you or anyone else going back to the code later can easily understand what it was for.
First, the code defines a variable to refer to the selected product in the subsequent code. Using thisProduct means you don’t have to refer to the specified product using the path this._parent._parent.products_dg.selectedItem.
26
Chapter 2: Creating an Application with Components (Flash Professional Only)
Next, the code populates the TextArea and Label instances by using the description, price, and priceQualifier properties of the thisProduct object. These properties correspond to elements in the products.xml file that you linked to the products_xmlcon XMLConnector instance at the beginning of the tutorial. Later in the tutorial, you’ll bind the XMLConnector, DataSet, and DataGrid component instances together, and the elements in the XML file will populate the other two component instances. Finally, the code uses the image property of the thisProduct object to load an image of the product into the Loader component. 3. Next you’ll add an event listener to add the product to the cart when the user clicks the Add to
Cart button. (You’ll add ActionScript to the main Timeline in the application later in the tutorial, to create an instance of the Cart class.) Add the following code: var cartListener:Object = new Object(); cartListener.click = function(evt:Object) { var tempObj:Object = new Object(); tempObj.quantity = evt.target._parent.quantity_ns.value; tempObj.id = thisProduct.id; tempObj.productObj = thisProduct; var theCart = evt.target._parent._parent._parent.myCart; theCart.addProduct(tempObj.quantity, thisProduct); }; addToCart_button.addEventListener("click", cartListener);
4. Click the Check Syntax button (the blue check mark above the Script pane) to make sure there
are no syntax errors in the code. You should check syntax frequently as you add code to an application. Any errors found in the code are listed in the Output panel. (When you check syntax, only the current script is checked; other scripts that may be in the FLA file are not checked.) For more information, see “Debugging your scripts” in Using ActionScript in Flash. 5. Click the arrow button at the top left of the document window or select View > Edit Document
to exit symbol editing mode and return to the main Timeline. Add components for the Checkout screen When the user clicks the Checkout button on the main screen, the Checkout screen appears. The Checkout screen provides forms where the user can enter billing, shipping, and credit card information. The checkout interface consists of components placed on a keyframe at Frame 10 in the application. You’ll use the Accordion component to create the checkout interface. The Accordion component is a navigator that contains a sequence of children that it displays one at a time. You’ll also add a Button component instance to create a Back button, so users can return to the main screen.
Build the application architecture
27
Later in the tutorial, you’ll create movie clips to use as children in the Accordion instance, to display the Billing, Shipping, and Credit Card Information panes. 1. In the main Timeline for the application, move the playhead to Frame 10 (labeled Checkout).
Make sure the Form layer is selected. 2. Insert a blank keyframe on Frame 10 in the Form layer (select the frame and select Insert >
Timeline > Blank Keyframe). 3. With the new keyframe selected, drag an instance of the Accordion component from the UI
Components folder in the Components panel onto the Stage. In the Property inspector, enter checkout_acc for the instance name. Set Width to 300 pixels and Height to 200 pixels. 4. Drag an instance of the Button component from the UI Components folder in the Components
panel onto the Stage. In the Property inspector, enter back_button for the instance name. Click the Parameters tab, and enter Back for the label property. About the Billing, Shipping, and Credit Card panes The Billing, Shipping, and Credit Card Information panes are built with movie clip instances that are displayed in the Accordion component instance. Each pane consists of two nested movie clips. The parent movie clip contains a ScrollPane component, used to display content in a scrollable area. The child movie clip contains Label and TextInput components where users can enter personal data, such as name, address, and so on. You’ll use the ScrollPane component to display the child movie clip so that the user can scroll through the information fields. Create movie clips for the Billing Information pane First you’ll create two movie clips that will display the Billing Information form fields: a parent movie clip with the ScrollPane component instance, and a child movie clip with the Label and TextArea component instances. 1. In the Library panel (Window > Library), click the options menu on the right side of the title
bar and select New Symbol. 2. In the Create New Symbol dialog box, enter checkout1_mc for Name and select Movie Clip
for Behavior. 3. Click the Advanced button. Under Linkage, select Export for ActionScript, leave Export in First
Frame selected, and click OK. A document window for the new symbol opens in symbol-editing mode. 4. Drag an instance of the ScrollPane component onto the Stage. 5. In the Property inspector, enter checkout1_sp for the instance name. Set the W and H
coordinates to 300, 135. Set the X and Y coordinates to 0, 0. 6. Click the Parameters tab. Set the contentPath property to checkout1_sub_mc.
The checkout1_sub_mc movie clip will appear inside the scroll pane, and will contain the Label and TextInput components. You’ll create this movie clip next. 7. From the Library options menu, select New Symbol.
28
Chapter 2: Creating an Application with Components (Flash Professional Only)
8. In the Create New Symbol dialog box, enter checkout1_sub_mc for Name and select Movie
Clip for Behavior. 9. Click the Advanced button. Under Linkage, select Export for ActionScript, leave Export in First
Frame selected, and click OK. A document window for the new symbol opens in symbol-editing mode. 10. Drag six instances of the Label component onto the Stage. Alternatively, you can drag one
instance onto the Stage, and Control-drag (Windows) or Option-drag (Macintosh) it on the Stage to make copies. Name and position the instances as follows: ■
■
■
■
■
■
For the first instance, enter firstname_lbl for the instance name and set the X and Y coordinates to 5, 5. Click the Parameters tab and enter First Name for text. For the second instance, enter lastname_lbl for the instance name and set the X and Y coordinates to 5, 35. Click the Parameters tab and enter Last Name for text. For the third instance, enter country_lbl for the instance name and set the X and Y coordinates to 5, 65. Click the Parameters tab and enter Country for text. For the fourth instance, enter province_lbl for the instance name and set the X and Y coordinates to 5, 95. Click the Parameters tab and enter Province/State for text. For the fifth instance, enter city_lbl for the instance name and set the X and Y coordinates to 5, 125. Click the Parameters tab and enter City for text. For the sixth instance, enter postal_lbl for the instance name and set the X and Y coordinates to 5, 155. Click the Parameters tab and enter Postal/Zip Code for text.
11. Drag six instances of the TextInput component onto the Stage. Place a TextInput instance
immediately to the right of each Label instance. For example, the X, Y coordinates of the first TextInput instance should be 105, 5. Name the TextInput instances as follows: ■
Name the first instance billingFirstName_ti.
■
Name the second instance billingLastName_ti.
■
Name the third instance billingCountry_ti.
■
Name the fourth instance billingProvince_ti.
■
Name the fifth instance billingCity_ti.
■
Name the sixth instance billingPostal_ti.
Sometimes content in a scroll pane can be cropped if it’s too close to the border of the pane. In the next few steps you’ll add a white rectangle to the checkout1_sub_mc movie clip so that the Label and TextInput instances are displayed properly. 12. In the Timeline, click the Add New Layer button. Drag the new layer below the existing layer.
(The layer with the rectangle should be on the bottom, so that the rectangle doesn’t interfere with the component display.) 13. Select Frame 1 of the new layer.
Build the application architecture
29
14. In the Tools panel, select the Rectangle tool. Set the Stroke color to None and the Fill color to
white. Click the Stroke Color control in the Tools panel and click the None button—the white swatch with a red line through it. Click the Fill Color control and click the white color swatch. 15. Drag to create a rectangle that extends beyond the bottom and right edges of the Label and
TextInput instances. Create movie clips for the Shipping Information pane The movie clips for the Shipping Information pane are very similar to those for the Billing Information pane. You’ll also add a CheckBox component, enabling users to populate the Shipping Information form fields with the same data they entered in the Billing Information pane. 1. Follow the earlier instructions (see “Create movie clips for the Billing Information pane”
on page 28) to create the movie clips for the Credit Card Information pane. Note these naming differences: ■
For the first movie clip, enter checkout2_mc for the symbol name and checkout2_sp for the instance name. In the Property inspector’s Parameters tab, set the contentPath property to checkout2_sub_mc.
■
For the second movie clip, enter checkout2_sub_mc for the symbol name.
■
For the TextInput instances, change “billing” to “shipping” in the instance names.
2. With the checkout2_sub_mc movie clip open in symbol-editing mode, drag an instance of the
CheckBox component onto the Stage and position it just above the first Label instance. Make sure to place this instance on Layer 1, along with the other component instances. 3. In the Property inspector, enter sameAsBilling_ch for the instance name. 4. Click the Parameters tab. Set the label property to Same As Billing Info.
Create movie clips for the Credit Card Information pane The movie clips for the Credit Card Information pane are also similar to those for the Billing and Shipping Information panes. However, the nested movie clip for the Credit Card Information pane has somewhat different fields than the other two panes, for credit card number and other card data. 1. Follow steps 1-11 of the Billing Information instructions (see “Create movie clips for the Billing
Information pane” on page 28) to create the movie clips for the Credit Card Information pane. Note these naming differences: ■
■
30
For the first movie clip, enter checkout3_mc for the symbol name and checkout3_sp for the instance name. In the Property inspector’s Parameters tab, set the contentPath property to checkout3_sub_mc. For the second movie clip, enter checkout3_sub_mc for the symbol name.
Chapter 2: Creating an Application with Components (Flash Professional Only)
2. Drag four instances of the Label component onto the Stage. Name and position the instances
as follows: ■
■
■
■
For the first instance, enter ccName_lbl for the instance name and set the X and Y coordinates to 5, 5. Click the Parameters tab and enter Name On Card for text. For the second instance, enter ccType_lbl for the instance name and set the X and Y coordinates to 5, 35. Click the Parameters tab and enter Card Type for text. For the third instance, enter ccNumber_lbl for the instance name and set the X and Y coordinates to 5, 65. Click the Parameters tab and enter Card Number for text. For the fourth instance, enter ccExp_lbl for the instance name and set the X and Y coordinates to 5, 95. Click the Parameters tab and enter Expiration for text.
3. Drag an instance of the TextInput component onto the Stage and position it to the right of the
ccName_lbl instance. Name the new instance ccName_cb. 4. Drag an instance of the ComboBox component onto the Stage and position it to the right of
the ccType_lbl instance. Name the new instance ccType_cb. 5. Drag another instance of the TextInput component onto the Stage and position it to the right
of the ccNumber_lbl instance. Name the new instance ccNumber_cb. 6. Drag two instances of the ComboBox component onto the Stage. Position one to the right of
the ccExp_lbl instance, and position the other one to the right of that. Name the first new instance ccMonth_cb, and name the second ccYear_cb. 7. Drag an instance of the Button component onto the Stage and position it at the bottom of the
form, below the ccMonth_cb instance. Name the new instance checkout_button. In the Property inspector’s Parameters tab, set the label property to Checkout. 8. Follow the instructions in steps 14-16 of the Billing Information instructions (see “Create
movie clips for the Billing Information pane” on page 28) to add a rectangle to the bottom of the form.
Bind components to display product information from an external source In the beginning of the tutorial, you added instances of the DataGrid, DataSet, and XMLConnector components to the Stage. You set the URL property for the XMLConnector (named products_xmlcon) to the location of an XML file containing product information for the Gift Ideas section of the application. Now you’ll use data binding features in the Flash authoring environment to bind the XMLConnector, DataSet, and DataGrid components together to use the XML data in the application. For general information on working with data binding and other features of the Flash data integration architecture, see Chapter 14, “Data Integration (Flash Professional Only)” in Using Flash. When you bind the components, the DataSet component will filter the list of products in the XML file according to the severity of the blunder that the user selects in the What Did You Do? section. The DataGrid component will display the list.
Bind components to display product information from an external source
31
Specify a schema for the XML data source When you connect to an external XML data source with the XMLConnector component, you need to specify a schema—a schematic representation which identifies the structure of the XML document. The schema tells the XMLConnector component how to read the XML data source. The easiest way to specify a schema is to import a copy of the XML file that you’re going to connect to, and use that copy as a schema. 1. Launch your web browser and go to www.flash-mx.com/mm/firstapp/problems.xml (the
location you set for the XMLConnector URL parameter). 2. Select File > Save As. 3. Save products.xml to the same location as the FLA file that you’re working on. 4. Select Frame 1 in the main Timeline. 5. On the Stage, select the products_xmlcon (XMLConnector) instance. 6. In the Component inspector, click the Schema tab. Click the Import button (on the right side
of the Schema tab, above the scroll pane). In the Open dialog box, locate the products.xml file that you imported in step 3, and click Open. The schema for the products.xml file appears in the scroll pane of the Schema tab. Bind the XMLConnector, DataSet, and DataGrid components You’ll use the Binding tab in the Component inspector to bind the XMLConnector, DataSet, and DataGrid component instances to one another. For information on working with data binding, see “Data binding (Flash Professional only)” in Using Flash. 1. With the products_xmlcon (XMLConnector) instance selected on the Stage, click the Bindings
tab in the Component inspector. 2. Click the Add Binding button. 3. In the Add Binding dialog box, select the results.products.product array item and click
OK. 4. In the Bindings tab, click the Bound To item in the Binding Attributes pane (the bottom pane,
showing attribute name-value pairs). 5. In the Value column for the Bound To item, click the magnifying glass icon to open the Bound
To dialog box. 6. In the Bound To dialog box, select the products_ds (DataSet) instance in the Component Path
pane. Select dataProvider:array in the Schema Location pane. Click OK. 7. In the Bindings tab, click the Direction item in the Binding Attributes pane. From the pop-up
menu in the Value column, select Out. This option means that the data will pass from the products_xmlcon instance to the products_ds instance (rather than passing in both directions, or passing from the DataSet instance to the XMLConnector instance).
32
Chapter 2: Creating an Application with Components (Flash Professional Only)
8. On the Stage, select the products_ds instance. In the Bindings tab of the Component inspector,
notice that the component’s data provider appears in the Binding List (the top pane of the Bindings tab). In the Binding Attributes pane, the Bound To parameter indicates that the products_ds instance is bound to the products_xmlcom instance, and the binding direction is In. In the next few steps you’ll bind the DataSet instance to the DataGrid instance so that the data that is filtered by the data set will be displayed in the data grid. 9. With the products_ds instance still selected, click the Add Binding button in the Bindings tab. 10. In the Add Binding dialog box, select the dataProvider: array item and click OK. 11. In the Bindings tab, make sure the dataProvider: array item is selected in the Binding List. 12. Click the Bound To item in the Binding Attributes pane. 13. In the Value column for the Bound To item, click the magnifying glass icon to open the Bound
To dialog box. 14. In the Bound To dialog box, select the products_dg (DataGrid) instance in the Component
Path pane. Select dataProvider:array in the Schema Location pane. Click OK.
Add ActionScript to the main Timeline With the application architecture and data binding in place, you’re ready to add ActionScript to the main Timeline to complete the application functionality. Create references to component class names Each component is associated with a class file that defines its methods and properties. In this section of the tutorial, you’ll add ActionScript to create references to the class names for the components used in the application. For some of these components, you have already added instances to the Stage. For others, you’ll add ActionScript later in the tutorial to create instances dynamically. Creating a references to the class name makes it easier to write ActionScript for the component because it enables code completion for component instances, so you can avoid using the fully qualified name. For example, when you create a reference to the class file for the ComboBox component, you can refer to instances of the ComboBox with the syntax instanceName:ComboBox, rather than instanceName:mx.controls.ComboBox. You’ll need these classes: WebService class This class populates the ComboBox instance with a list of “problems.” For this class, you’ll also need to import the WebServiceClasses item from the Classes common library. This item contains compiled clips (SWC files) that you’ll need in order to compile and generate the SWF file for your application.
Add ActionScript to the main Timeline
33
UI Components Controls package
This package contains classes for the user interface control components, including ComboBox, DataGrid, Loader, TextInput, Label, NumericStepper, Button, and CheckBox. A package is a directory that contains class files and resides in a designated classpath directory. You can use a wild card to create references to all the classes in a package: for example, the syntax mx.controls.* creates references to all classes in the controls package. (When you create a reference to a package with a wild card, the unused classes are dropped from the application when it is compiled, so they don’t add any extra size.) UI Components Containers package This package contains classes for the user interface container components, including Accordion, ScrollPane, and Window. As with the controls package, you can create a reference to this package by using a wild card. DataGridColumn class
This class lets you add columns to the DataGrid instance and control
their appearance. Cart class
A custom class provided with this tutorial, the Cart class defines the functioning of the shopping cart that you’ll create later. (To examine the code in the Cart class file, open the cart.as file located in the component_application folder with the application FLA and SWF files). You’ll create an Actions layer and add ActionScript code to the first frame of the main Timeline. For all the code that you’ll add to the application in the remaining steps of the tutorial, make sure you place it on the Actions layer. 1. To import the WebServiceClasses item from the Classes library, select Window > Other
Panels > Common Libraries > Classes. 2. Drag the WebServiceClasses item from the Classes library into the library for the application.
Importing an item from the Classes library is similar to adding a component to the library: it adds the SWC files for the class to the library. The SWC files need to be in the library in order for you to use the class in an application. 3. In the Timeline, select the Form layer and click the Add New Layer button. Name the new layer
Actions. 4. With the Actions layer selected, select Frame 1 and press F9 to open the Actions panel. 5. In the Actions panel, enter the following code to create a stop() function that prevents the
application from looping during playback: stop();
6. With Frame 1 in the Actions layer still selected, add the following code in the Actions panel to
import the classes: // import necessary classes import mx.services.WebService; import mx.controls.*; import mx.containers.*; import mx.controls.gridclasses.DataGridColumn; // import the custom Cart class import Cart;
34
Chapter 2: Creating an Application with Components (Flash Professional Only)
Add an instance of the Cart class and initialize it The next code that you’ll add creates an instance of the custom Cart class and then initializes the instance.
• In the Actions panel, add the following code: var myCart:Cart = new Cart(this); myCart.init();
This code uses the init() method of the Cart class to add a DataGrid instance to the Stage, define the columns, and position the DataGrid instance on the Stage. It also adds a Button component instance and positions it, and adds an Alert handler for the button. (To see the code for the Cart class init() method, open the Cart.as file.) Set the data type of component instances Next you’ll assign data types to each of the component instances you dragged to the Stage earlier in the tutorial. ActionScript 2.0 uses strict data typing, which means that you assign the data type when you create a variable. Strict data typing makes code hints available for the variable in the Actions panel.
• In the Actions panel, add the following code to assign data types to the four component instances that you already created. // data type instances on the Stage; other instances might be added at // runtime from the Cart class var problems_cb:ComboBox; var products_dg:DataGrid; var cart_dg:DataGrid; var products_xmlcon:mx.data.components.XMLConnector;
Use styles to customize component appearance Each component has style properties and methods that let you customize its appearance, including highlight color, font, and font size. You can set styles for individual component instances, or set styles globally to apply to all component instances in an application. For this tutorial you’ll set styles globally.
• Add the following code to set styles: // define global styles and easing equations for the problems_cb ComboBox _global.style.setStyle("themeColor", "haloBlue"); _global.style.setStyle("fontFamily", "Verdana"); _global.style.setStyle("fontSize", 10); _global.style.setStyle("openEasing", mx.transitions.easing.Bounce.easeOut);
This code sets the theme color (the highlight color on a selected item), font, and font size for the components, and also sets the easing for the ComboBox—the way that the drop-down menu appears and disappears when you click the ComboBox title bar.
Add ActionScript to the main Timeline
35
Add columns to the Gift Ideas section Now you’re ready to add columns to the data grid in the Gift Ideas section of the application, for displaying product information and price.
• In the Actions panel, add the following code to create, configure, and add a Name column and a Price column to the DataGrid instance: // define data grid columns and their default widths in the products_dg // DataGrid instance var name_dgc:DataGridColumn = new DataGridColumn("name"); name_dgc.headerText = "Name"; name_dgc.width = 280; // add the column to the DataGrid products_dg.addColumn(name_dgc); var price_dgc:DataGridColumn = new DataGridColumn("price"); price_dgc.headerText = "Price"; price_dgc.width = 100; // define the function that will be used to set the column’s label // at runtime price_dgc.labelFunction = function(item:Object) { if (item != undefined) { return "$"+item.price+" "+item.priceQualifier; } }; products_dg.addColumn(price_dgc);
Connect to a web service to populate the combo box In this section you’ll add code to connect to a web service that contains the list of blunders (Forgot to Water Your Plants, and so on). The web service description language (WSDL) file is located at www.flash-mx.com/mm/firstapp/problems.cfc?WSDL. To see how the WSDL is structured, point your browser to the WSDL location. The ActionScript code passes the web service results to the ComboBox instance for display. A function sorts the blunders in order of severity. If no result is returned from the web service (for example, if the service is down, or the function isn’t found), an error message appears in the Output panel.
• In the Actions panel, add the following code: /* Define the web service used to retrieve an array of problems. This service will be bound to the problems_cb ComboBox instance. */ var problemService:WebService = new WebService("http://www.flash-mx.com/mm/ firstapp/problems.cfc?WSDL"); var myProblems:Object = problemService.getProblems(); /* If you get a result from the web service, set the field that will be used for the column label. Set the data provider to the results returned from the web service. */ myProblems.onResult = function(wsdlResults:Array) { problems_cb.labelField = "name"; problems_cb.dataProvider = wsdlResults.sortOn("severity", Array.NUMERIC);
36
Chapter 2: Creating an Application with Components (Flash Professional Only)
}; // If you are unable to connect to the remote web service, display the // error messages in the Output panel. myProblems.onFault = function(error:Object) { trace("error:"); for (var prop in error) { trace(" "+prop+" -> "+error[prop]); } };
Load the external XML file listing product information Next you’ll add a line of code that causes the XMLConnector instance to load, parse, and bind the contents of the remote products.xml file. This file is located at the URL you entered for the URL property of the XMLConnector instance that you created earlier. The file contains information on the products that will appear in the Gift Ideas section of the application.
• Add the following code in the Actions panel: products_xmlcon.trigger();
Add an event listener to filter the products displayed in the Gift Ideas section You’ll add an event listener to detect when a user selects a blunder in the What Did You Do? section (the problems_cb ComboBox instance). The listener includes a function that filters the Gift Ideas list according to the blunder the user chooses. Selecting a minor blunder displays a list of modest gifts (such as a CD or flowers); selecting a more serious blunder displays more opulent gifts. For more information on working with event listeners, see “Using event listeners” in Using ActionScript in Flash.
• In the Actions panel, add the following code: /* Define a listener for the problems_cb ComboBox instance. This listener will filter the products in the DataSet (and DataGrid). Filtering is based on the severity of the currently selected item in the ComboBox. */ var cbListener:Object = new Object(); cbListener.change = function(evt:Object) { products_ds.filtered = false; products_ds.filtered = true; products_ds.filterFunc = function(item:Object) { // If the current item's severity is greater than or equal to the selected // item in the ComboBox, return true. return (item.severity>=evt.target.selectedItem.severity); }; }; // Add the listener to the ComboBox. problems_cb.addEventListener("change", cbListener);
Add ActionScript to the main Timeline
37
Resetting the filtered property (setting it to false and then to true) at the beginning of the change() function ensures that the function will work properly if the user changes the What Did You Do? selection repeatedly. The filterFunc function checks whether a given item in the array of gifts falls within the severity the user selected in the combo box. If the gift is within the selected severity range, it is displayed in the DataGrid instance (which is bound to the DataSet instance). The last line of code registers the listener to the problems_cb ComboBox instance. Add an event listener to display product details Next you’ll add an event listener to the products_dg DataGrid instance to display information about each product. When the user clicks a product in the Gift Ideas section, a pop-up window appears with information about the product.
• In the Actions panel, add the following code: // create a listener for the DataGrid to detect when the row in the // DataGrid is changed var dgListener:Object = new Object(); dgListener.change = function(evt:Object) { // when the current row changes in the DataGrid, launch a new pop-up // window displaying the product's details myWindow = mx.managers.PopUpManager.createPopUp(_root, mx.containers.Window, true, {title:evt.target.selectedItem.name, contentPath:"ProductForm", closeButton:true}); // set the dimensions of the pop-up window myWindow.setSize(340, 210); // define a listener that closes the pop-up window when the user clicks // the close button var closeListener:Object = new Object(); closeListener.click = function(evt) { evt.target.deletePopUp(); }; myWindow.addEventListener("click", closeListener); }; products_dg.addEventListener("change", dgListener);
This code creates a new event listener called dgListener, and creates instances of the Window component you added to the library earlier. The title for the new window is set to the product’s name. The content path for the window is set to the ProductForm movie clip. The size of the window is set to 340 x 210 pixels. The code also adds a close button to enable the user to close the window after viewing the information.
38
Chapter 2: Creating an Application with Components (Flash Professional Only)
Add an event listener to the Checkout button Now you’ll add code to display the Checkout screen when the user clicks the Checkout button.
• In the Actions panel, add the following code: // when the Checkout button is clicked, go to the "checkout" frame label var checkoutBtnListener:Object = new Object(); checkoutBtnListener.click = function(evt:Object) { evt.target._parent.gotoAndStop("checkout"); }; checkout_button.addEventListener("click", checkoutBtnListener);
This code specifies that, when the user clicks the Checkout button, the playhead moves to the Checkout label in the Timeline. Add code for the Checkout screen Now you’re ready to add code to the Checkout screen of the application, on Frame 10 on the main Timeline. This code processes the data that users enter in the Billing, Shipping, and Credit Card Information panes that you created earlier with the Accordion component and other components. 1. In the Timeline, select Frame 10 in the Actions layer and insert a blank keyframe (select Insert >
Timeline > Blank Keyframe) 2. Open the Actions panel (F9). 3. In the Actions panel, add the following code: stop(); import mx.containers.*; // define the Accordion component on the Stage var checkout_acc:Accordion;
4. Next you’ll add the first child to the Accordion component instance, to accept billing
information from the user. Add the following code: // define the children for the Accordion component var child1 = checkout_acc.createChild("checkout1_mc", "child1_mc", {label:"1. Billing Information"}); var thisChild1 = child1.checkout1_sp.spContentHolder;
The first line calls the createChild() method of the Accordion component and creates an instance of the checkout1_mc movie clip symbol (which you created earlier) with the instance name child1_mc and the label “1. Billing Information”. The second line of code creates a shortcut to an embedded ScrollPane component instance. 5. Create the second child for the Accordion instance, to accept shipping information: /* Add the second child to the Accordion. Add an event listener for the sameAsBilling_ch CheckBox. This copies the form values from the first child into the second child. */ var child2 = checkout_acc.createChild("checkout2_mc", "child2_mc", {label:"2. Shipping Information"}); var thisChild2 = child2.checkout2_sp.spContentHolder; var checkboxListener:Object = new Object();
The first two lines of code are similar to the code for creating the Billing Information child: you create an instance of the checkout2_mc movie clip symbol, with the instance name child2_mc and the label “2. Shipping Information”. The second line of code creates a shortcut to an embedded ScrollPane component instance. Beginning with the third line of code, you add an event listener to the CheckBox instance. If the user clicks the check box, the shipping information uses the data the user entered in the Billing Information pane. 6. Next, create a third child for the Accordion instance, for credit card information: // define the third Accordion child var child3 = checkout_acc.createChild("checkout3_mc", "child3_mc", {label:"3. Credit Card Information"}); var thisChild3 = child3.checkout3_sp.spContentHolder;
7. Add this code to create ComboBox instances for the credit card month, year, and type, and
populate each with a statically defined array: /* set the values in the three ComboBox instances on the Stage: ccMonth_cb, ccYear_cb and ccType_cb */ thisChild3.ccMonth_cb.labels = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; thisChild3.ccYear_cb.labels = [2004, 2005, 2006, 2007, 2008, 2009, 2010]; thisChild3.ccType_cb.labels = ["VISA", "MasterCard", "American Express", "Diners Club"];
8. Finally, add the following code to add event listeners to the Checkout button and the Back
button. When the user clicks the Checkout button, the listener object copies the form fields from the Billing, Shipping, and Credit Card Information panes into a LoadVars object that is sent to the server. (The LoadVars class lets you send all the variables in an object to a specified URL.) When the user clicks the Back button, the application returns to the main screen. /* Create a listener for the checkout_button Button instance. This listener sends all the form variables to the server when the user clicks the Checkout button. */ var checkoutListener:Object = new Object(); checkoutListener.click = function(evt:Object); evt.target.enabled = false; /* Create two LoadVars object instances, which send variables to and receive results from the remote server. */
40
Chapter 2: Creating an Application with Components (Flash Professional Only)
var response_lv:LoadVars = new LoadVars(); var checkout_lv:LoadVars = new LoadVars(); checkout_lv.billingFirstName = thisChild1.billingFirstName_ti.text; checkout_lv.billingLastName = thisChild1.billingLastName_ti.text; checkout_lv.billingCountry = thisChild1.billingCountry_ti.text; checkout_lv.billingProvince = thisChild1.billingProvince_ti.text; checkout_lv.billingCity = thisChild1.billingCity_ti.text; checkout_lv.billingPostal = thisChild1.billingPostal_ti.text; checkout_lv.shippingFirstName = thisChild2.shippingFirstName_ti.text; checkout_lv.shippingLastName = thisChild2.shippingLastName_ti.text; checkout_lv.shippingCountry = thisChild2.shippingCountry_ti.text; checkout_lv.shippingProvince = thisChild2.shippingProvince_ti.text; checkout_lv.shippingCity = thisChild2.shippingCity_ti.text; checkout_lv.shippingPostal = thisChild2.shippingPostal_ti.text; checkout_lv.ccName = thisChild3.ccName_ti.text; checkout_lv.ccType = thisChild3.ccType_cb.selectedItem; checkout_lv.ccNumber = thisChild3.ccNumber_ti.text; checkout_lv.ccMonth = thisChild3.ccMonth_cb.selectedItem; checkout_lv.ccYear = thisChild3.ccYear_cb.selectedItem; /* Send the variables from the checkout_lv LoadVars to the remote script on the server. Save the results in the response_lv instance. */ checkout_lv.sendAndLoad("http://www.flash-mx.com/mm/firstapp/cart.cfm", response_lv, "POST"); response_lv.onLoad = function(success:Boolean) { evt.target.enabled = true; }; }; thisChild3.checkout_button.addEventListener("click", checkoutListener); cart_mc._visible = false; var backListener:Object = new Object(); backListener.click = function(evt:Object) { evt.target._parent.gotoAndStop("home"); } back_button.addEventListener("click", backListener);
Test the application Congratulations! You’ve finished building the application. Now you’re ready to test it. If you find any errors during testing, check your application against the finished sample (first_app_v3.fla) to correct any mistakes. Try using the procedures demonstrated in this tutorial to build component-based applications of your own. 1. Select Control > Test Movie or press Control+Enter (Windows) or Command+Return
(Macintosh). 2. Click through the application to test it: select a blunder, choose a gift, and add checkout
information.
Test the application
41
42
Chapter 2: Creating an Application with Components (Flash Professional Only)
CHAPTER 3 Working with Components
In this chapter, you’ll use several Macromedia Flash (FLA) files and ActionScript class files to learn how to add components to a document and set their properties. This chapter also explains a few advanced topics such as using code hints, creating custom focus navigation, managing component depth, and upgrading version 1 components to version 2 architecture. The files used in this chapter are TipCalulator.fla and TipCalculator.swf. The files are installed in the following locations on your hard disk:
The Components panel All components in the user-level configuration/Components directory are displayed in the Components panel. (For more information about this directory, see “Where component files are stored” on page 13.) To display the Components panel:
• Select Window > Development Panels > Components. Components panel menu
To display components that were installed after Flash started up:
1. Select Window > Development Panels > Components. 2. Select Reload from the Components panel menu.
Adding components to Flash documents When you drag a component from the Components panel to the Stage, a compiled clip (SWC) symbol is added to the Library panel. Once a compiled clip symbol is in the library, you can drag multiple instances to the Stage. You can also add that component to a document at runtime by using the UIObject.createClassObject() ActionScript method. Adding components during authoring You can add a component to a document by using the Components panel, and then add additional instances of the component to the document by dragging the component from the Library panel to the Stage. You can set properties for additional instances in the Parameters tab of the Property inspector or in the Parameters tab in the Component inspector. To add a component to a Flash document by using the Components panel:
1. Select Window > Development Panels > Components. 2. Do one of the following:
44
■
Drag a component from the Components panel to the Stage.
■
Double-click a component in the Components panel.
Chapter 3: Working with Components
3. If the component is a FLA (all installed version 2 components are SWC files) and if you have
edited skins for another instance of the same component, or for a component that shares skins with the component you are adding, do one of the following: ■
■
Select Don’t Replace Existing Items to preserve the edited skins and apply the edited skins to the new component. Select Replace Existing Items to replace all the skins with default skins. The new component and all previous versions of the component, or of components that share its skins, will use the default skins.
4. Select the component on the Stage. 5. Select Window > Properties. 6. In the Property inspector, enter an instance name for the component instance. 7. Click the Parameters tab and specify parameters for the instance.
The following illustration shows a the Property inspector for the TextInput component that is in the TipCalculator.fla sample file (installed at Flash MX 2004/Samples/HelpExamples/ TipCalculator).
For more information, see “Setting component parameters” on page 47. 8. Change the size of the component as desired.
For more information on sizing specific component types, see the individual component entries in Chapter 6, “Components Dictionary,” on page 91. 9. If you want to change the color and text formatting of a component, do one or more of
the following: ■
Set or change a specific style property value for a component instance by using the method, which is available to all components. For more information, see UIObject.setStyle() on page 825.
setStyle()
■
Edit multiple properties in the global style declaration assigned to all version 2 components.
■
Create a custom style declaration for specific component instances. For more information, see “Using styles to customize component color and text” on page 67.
10. If you want to customize the appearance of the component, do one of the following: ■
Apply a theme (see “About themes” on page 77).
■
Edit a component’s skins (see “About skinning components” on page 80).
Adding components to Flash documents
45
Adding components at runtime with ActionScript Use the createClassObject() method (which most components inherit from the UIObject class) to add components to a Flash application dynamically. For example, you could add components that create a page layout based on user-set preferences (as on the home page of a web portal). Version 2 components that are installed with Flash MX 2004 reside in package directories. (For more information, see “Using packages” in Using ActionScript in Flash.) If you add a component to the Stage during authoring, you can refer to the component simply by using its instance name (for example, myButton). However, if you add a component to an application with ActionScript (at runtime), you must either specify its fully qualified class name (for example, mx.controls.Button) or import the package by using the import statement. For example, to write ActionScript code that refers to an Alert component, you can use the statement to reference the class, as follows:
import
import mx.controls.Alert; Alert.show("The connection has failed", "Error");
Alternatively, you can use the full package path, as follows: mx.controls.Alert.show("The connection has failed", "Error");
For more information, see “Importing classes” in Using ActionScript in Flash. You can use ActionScript methods to set additional parameters for dynamically added components. For more information, see Chapter 6, “Components Dictionary,” on page 91. To add a component to a document at runtime, it must be in the library when the SWF file is compiled. To add a component to the library, add it to the Stage and delete it. Note: The instructions in this section assume an intermediate or advanced knowledge of ActionScript. To add a component to your Flash document using ActionScript:
1. Drag a component to the Stage and delete it.
If you do this, you must select the Export in First Frame check box in the Linkage Properties dialog box of the component in the library. Note: If a component is set to Export in First Frame, you can’t preload the component.
2. Select the frame in the Timeline where you want to add the component. 3. Open the Actions panel if it isn’t already open. 4. Call createClassObject() to create the component instance at runtime.
This method can be called on its own, or from any component instance. The createClassObject() method takes the following parameters: a component class name, an instance name for the new instance, a depth, and an optional initialization object that you can use to set properties at runtime. You can specify the class package in the class name parameter, as in this example: createClassObject(mx.controls.CheckBox, "cb", 5, {label:"Check Me"});
46
Chapter 3: Working with Components
Alternatively, you can import the class package, as in this example: import mx.controls.CheckBox; createClassObject(CheckBox, "cb", 5, {label:"Check Me"});
For more information, see UIObject.createClassObject() on page 810 and Chapter 4, “Handling Component Events,” on page 55.
Components in the Library panel When you add a component to a document, it is displayed as a compiled clip (SWC file) symbol in the Library panel.
A ComboBox component in the Library panel You can add more instances of a component by dragging the component icon from the library to the Stage. For more information about compiled clips, see “About compiled clips and SWC files” on page 17.
Setting component parameters Each component has parameters that you can set to change its appearance and behavior. A parameter is a property that appears in the Property inspector and Component inspector. The most commonly used properties appear as authoring parameters; others must be set with ActionScript. All parameters that can be set during authoring can also be set with ActionScript. Setting a parameter with ActionScript overrides any value set during authoring. All version 2 components inherit properties and methods from the UIObject and UIComponent classes; these are the properties and methods that all components use, such as UIObject.setSize(), UIObject.setStyle(), UIObject.x, and UIObject.y. Each component also has unique properties and methods, some of which are available as authoring parameters. For example, the ProgressBar component has a percentComplete property (ProgressBar.percentComplete), and the NumericStepper component has nextValue and previousValue properties (NumericStepper.nextValue, NumericStepper.previousValue).
Setting component parameters
47
You can set parameters for a component instance using the Component inspector or the Property inspector (it doesn’t matter which panel you use). To enter an instance name for a component in the Property inspector:
1. Select Window > Properties. 2. Select an instance of a component on the Stage. 3. Enter an instance name in the text field under the word Component.
It’s a good idea to add a suffix to the instance name that indicates what kind of component it is; this makes it easier to read your ActionScript code. In this example, the instance name is states_cb because the component is a combo box that lists the US states.
To enter parameters for a component instance in the Component inspector:
1. Select Window > Development Panels > Component Inspector. 2. Select an instance of a component on the Stage. 3. To enter parameters, click the Parameters tab.
4. To enter or view bindings or schemas for a component, click their respective tabs. For more
information, see Chapter 14, “Data Integration (Flash Professional Only),” in Using Flash.
48
Chapter 3: Working with Components
Sizing components Use the Free Transform tool or the setSize() method to resize component instances.
Resizing the Menu component on the Stage with the Free Transform tool You can call the setSize() method from any component instance (see UIObject.setSize() on page 823) to resize it. The following code resizes the Menu component to 200 pixels wide and 300 pixels high: myMenu.setSize(200, 300); Note: If you use the ActionScript _width and _height properties to adjust the width and height of a component, the component is resized but the layout of the content in the component remains the same. This might cause the component to be distorted in movie playback.
A component does not resize automatically to fit its label. If a component instance that has been added to a document is not large enough to display its label, the label text is clipped. You must resize the component to fit its label.
A clipped label for the CheckBox component For more information about sizing components, see their individual entries in Chapter 6, “Components Dictionary,” on page 91.
Sizing components
49
Deleting components from Flash documents To delete a component’s instances from a Flash document, you must delete the component from the library by deleting the compiled clip icon. It isn’t enough to delete the component from the Stage. To delete a component from a document:
1. In the Library panel, select the compiled clip (SWC) symbol. 2. Click the Delete button at the bottom of the Library panel, or select Delete from the Library
options menu. 3. In the Delete dialog box, click Delete to confirm the deletion.
Using code hints When you are using ActionScript 2.0, you can use strict typing for a variable that is based on a built-in class, including component classes. If you do so, the ActionScript editor displays code hints for the variable. For example, suppose you type the following: import mx.controls.CheckBox; var myCheckBox:CheckBox; myCheckBox.
As soon as you type the period after myCheckBox, Flash displays a list of methods and properties available for CheckBox components, because you have designated the variable as type CheckBox. For more information, see “Strict data typing” and “Using code hints” in Using ActionScript in Flash.
Creating custom focus navigation When a user presses the Tab key to navigate in a Flash application or clicks in an application, the FocusManager class determines which component receives input focus. You don’t need to add a FocusManager instance to an application or write any code to activate the Focus Manager. If a RadioButton object receives focus, the Focus Manager examines that object and all objects with the same groupName value and sets focus on the object with the selected property set to true. Each modal Window component contains an instance of the Focus Manager, so the controls on that window become their own tab set. This prevents a user from inadvertently navigating to components in other windows by pressing the Tab key. To create focus navigation in an application, set the tabIndex property on any components (including buttons) that should receive focus. When a user presses the Tab key, the FocusManager class looks for an enabled object whose tabIndex value is greater than the current value of tabIndex. Once the FocusManager class reaches the highest tabIndex property, it returns to 0. For example, in the following code, the comment object (probably a TextArea component) receives focus first, and then the okButton object receives focus: var comment:mx.controls.TextArea; var okButton:mx.controls.Button;
50
Chapter 3: Working with Components
comment.tabIndex = 1; okButton.tabIndex = 2;
You can also use the Accessibility panel to assign a tab index value. If nothing on the Stage has a tab index value, the Focus Manager uses the depth levels (z-order). The depth levels are set up primarily by the order in which components are dragged to the Stage; however, you can also use the Modify > Arrange > Bring to Front/Send to Back commands to determine the final z-order. To give focus to a component in an application, call focusManager.setFocus(). To create a button that receives focus when a user presses Enter (Windows) or Return (Macintosh), set the FocusManager.defaultPushButton property to the instance of the desired button, as in the following code: focusManager.defaultPushButton = okButton;
The FocusManager class overrides the default Flash Player focus rectangle and draws a custom focus rectangle with rounded corners. For more information about creating a focus scheme in a Flash application, see “FocusManager class” on page 419.
Managing component depth in a document If you want to position a component in front of or behind another object in an application, you must use the DepthManager class. The methods of the DepthManager class allows you to place user interface components in an appropriate z-order (for example, a combo box drops down in front of other components, insertion points appear in front of everything, dialog boxes float over content, and so on). The Depth Manager has two main purposes: to manage the relative depth assignments within any document, and to manage reserved depths on the root Timeline for system-level services such as the cursor and tooltips. To use the Depth Manager, call its methods (see “DepthManager class” on page 406). The following code places the component instance loader below the button component: loader.setDepthBelow(button);
Managing component depth in a document
51
Components in Live Preview The Live Preview feature, enabled by default, lets you view components on the Stage as they will appear in the published Flash content; the components appear at their approximate size. The live preview reflects different parameters for different components. For information about which component parameters are reflected in the live preview, see each component entry in Chapter 6, “Components Dictionary,” on page 91.
A Button component with Live Preview enabled
A Button component with Live Preview disabled Components in Live Preview are not functional. To test component functionality, you can use the Control > Test Movie command. To turn Live Preview on or off:
• Select Control > Enable Live Preview. A check mark next to the option indicates that it is enabled.
About using a preloader with components Components are set to Export in First Frame by default. This causes the components to load before the first frame of an application is rendered. If you want to create a preloader for an application, deselect Export in First Frame for any compiled clip symbols in your library. Note: If you’re using the ProgressBar component to display loading progress, leave Export in First Frame selected for the progress bar.
About loading components If you load version 2 components into a SWF or into the Loader component, the components may not work correctly. These components include the following: Alert, ComboBox, DateField, Menu, MenuBar, and Window. Use the _lockroot property when calling loadMovie() or loading into the Loader component. If you’re using the Loader component, add the following code: myLoaderComponent.content._lockroot = true;
If you’re using a movie clip with a call to loadMovie(), add the following code: myMovieClip._lockroot = true;
If you don’t set _lockroot to true in the loader movie, the loader only has access to its own library, but not the library in the loaded movie. The _lockroot property is supported by Flash Player 7. For information about this property, see MovieClip._lockroot in Flash ActionScript Language Reference.
52
Chapter 3: Working with Components
Upgrading version 1 components to version 2 architecture The version 2 components were written to comply with several web standards (regarding events [www.w3.org/TR/DOM-Level-3-Events/events.html], styles, getter/setter policies, and so on) and are very different from their version 1 counterparts that were released with Macromedia Flash MX and in the DRKs that were released before Macromedia Flash MX 2004. Version 2 components have different APIs and were written in ActionScript 2.0. Therefore, using version 1 and version 2 components together in an application can cause unpredictable behavior. For information about upgrading version 1 components to use version 2 event handling, styles, and getter/setter access to the properties instead of methods, see Chapter 7, “Creating Components,” on page 915. Flash applications that contain version 1 components work properly in Flash Player 6 and Flash Player 7, when published for Flash Player 6 or Flash Player 6 (6.0.65.0). If you want to update your applications to work when published for Flash Player 7, you must convert your code to use strict data typing. For more information, see Chapter 10, “Creating Custom Classes with ActionScript 2.0,” in Using ActionScript in Flash.
Upgrading version 1 components to version 2 architecture
53
54
Chapter 3: Working with Components
CHAPTER 4 Handling Component Events
Every component has events that are broadcast when a user interacts with it (for example, the click and change events) or when something significant happens to the component (for example, the load event). To handle an event, you write ActionScript code that executes when the event occurs. Each component broadcasts its own set of events. This set includes the events of any class from which the component inherits. This means that all components, except the media components, inherit events from the UIObject and UIComponent classes, because they are the base classes of the version 2 architecture. To see the list of events a component broadcasts, see the component’s entry and its ancestor classes’ entries in Chapter 6, “Components Dictionary,” on page 91. This chapter uses several versions of a simple Macromedia Flash application, TipCalculator, to teach you how to handle component events. The FLA and SWF files are installed with Flash MX 2004 version 7.2 to the Macromedia/Flash MX 2004/Samples/HelpExamples/TipCalculator folder. This chapter contains the following sections: Using the on() event handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Using listeners to handle events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Delegating events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 About the event object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Using the on() event handler The easiest, but least powerful, way to handle a component event is to use the on() event handler. You can assign the on() event handler to a component instance, just as you would assign a handler to a button or movie clip. For complex applications, it’s best to use event listeners. For more information, see “Using listeners to handle events” on page 56.
55
The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the Button component instance myButton, sends “_level0.myButton” to the Output panel: on(click){ trace(this); } To use the on() event handler:
1. Open the file TipCalculator1.fla from Macromedia\Flash MX
2004\Samples\HelpExamples\TipCalculator. 2. On the Stage, select the TextInput component beside the “Enter subtotal” text.
3. Open the Actions panel, if it isn’t already open. 4. Look at the following code assigned to the subtotal_ti TextInput component: on(change){ this._parent.calculate(); }
This code calls the calculate() function that is defined on Frame 1 of the main Timeline when the TextInput component changes. The calculate() function calculates the tip according to which radio button is selected. 5. Select each of the radio buttons to see their event handlers.
Each radio button also calls the calculate() function when clicked. 6. Select Control > Test Movie to use the tip calculator.
Using listeners to handle events The version 2 component architecture has a broadcaster/listener event model. (A broadcaster is sometimes also referred to as a dispatcher.) It is important to understand the following key points about the model:
• All events are broadcast by an instance of a component class. (The component instance is the broadcaster.)
• A listener can be a function or an object. If the listener is an object, it must have a callback function defined on it. The listener handles the event; this means the function, or callback function, executes when the event occurs.
56
Chapter 4: Handling Component Events
• To register a listener to a broadcaster, call the addEventListener() method from the broadcaster. Use the following syntax: componentInstance.addEventListener("eventName", listenerObjectORFunction);
• You can register multiple listeners to one component instance. myButton.addEventListener("click", listener1); myButton.addEventListener("click", listener2);
• You can register one listener to multiple component instances. myButton.addEventListener("click", listener1); myButton2.addEventListener("click", listener1);
• The handler function is passed an event object. You can use the event object in the body of the function to retrieve information about the event type, and the instance that broadcast the event. See “About the event object” on page 66. Using listener objects To use a listener object, you can either use the this keyword to specify the current object as the listener, use an object that already exists in your application, or create a new object.
• Use this in most situations. It’s often easiest to use the current object (this) as a listener, because its scope contains the components that need to react when the event is broadcast.
• Use an existing object if it is convenient. For example, in a Flash Form Application, you may want to use a form as a listener object if that form contains the components that react to the event. Place the code on a frame of the form’s Timeline.
• Use a new listener object if many components are broadcasting an event (for example, the click
event) and you want only certain listener objects to respond.
If you use the this object, define a function with the same name as the event you want to handle; the syntax is as follows: function eventName(evtObj:Object){ // your code here };
If you want to use a new listener object, you must create the object, define a property with the same name as the events, and assign the property to a callback function that executes when the event is broadcast, as follows: var listenerObject:Object = new Object(); listenerObject.eventName = function(evtObj:Object){ // your code here };
If you want to use an existing object, use the same syntax as a new listener object, without creating the new object, as shown here: existingObject.eventName = function(evtObj:Object){
Using listeners to handle events
57
// your code here }; Tip: The evtObj parameter is an object that is automatically generated when an event is triggered and passed to the callback function. The event object has properties that contain information about the event. For details, see “About the event object” on page 66.
Finally, you call the addEventListener() method from the component instance that broadcasts the event. The addEventListener() method takes two parameters: a string indicating the name of the event and a reference to the listener object. componentInstance.addEventListener("eventName", listenerObject);
Here is the whole code segment, which you can copy and paste. Be sure to replace any code in italics with actual values; you can use listenerObject and evtObj or any other legal identifiers, but you must change eventName to the name of the event. var listenerObject:Object = new Object(); listenerObject.eventName = function(evtObj:Object){ // code placed here executes // when the event is triggered }; componentInstance.addEventListener("eventName", listenerObject);
The following code segment uses the this keyword as the listener object: function eventName(evtObj:Object){ // code placed here executes // when the event is triggered } componentInstance.addEventListener("eventName", this);
You can call addEventListener() from any component instance; it is mixed in to every component from the EventDispatcher class. (A “mix-in” is a class that provides specific features that augment the behavior of another class.) For more information, see EventDispatcher.addEventListener() on page 416. For information about the events a component broadcasts, see the component’s entry in Chapter 6, “Components Dictionary,” on page 91. For example, Button component events are listed in the Button component section (or Help > Using Components > Components Dictionary > Button component > Button class > Event summary for the Button class). To register a listener object in a Flash (FLA) file:
1. In Flash, select File > New and create a new Flash document. 2. Drag a Button component to the Stage from the Components panel. 3. In the Property inspector, enter the instance name myButton. 4. Drag a TextInput component to the Stage from the Components panel. 5. In the Property inspector, enter the instance name myText. 6. Select Frame 1 in the Timeline. 7. Select Window > Development Panels > Actions.
58
Chapter 4: Handling Component Events
8. In the Actions panel, enter the following code: var myButton:mx.controls.Button; var myText:mx.controls.TextInput; function click(evt){ myText.text = evt.target; } myButton.addEventListener("click", this);
The target property of the event object, evt, is a reference to the instance broadcasting the event. This code displays the value of the target property in the TextInput component. To register a listener object in a class (AS) file:
1. Open the file TipCalculator.fla from the location specified in “Working with Components”
on page 43. 2. Open the file TipCalculator.as from the location specified in “Working with Components”
on page 43. 3. In the FLA file, select form1 and view the class name, TipCalculator, in the Property inspector.
This is the link between the form and the class file. All the code for this application is in the file TipCalculator.as. The form assumes the properties and behaviors defined by the class assigned to it. 4. In the AS file, scroll to line 25, public function onLoad():Void.
The onLoad() function executes when the form loads into Flash Player. In the body of the function, the subtotal TextInput instance and the three RadioButton instances, percentRadio15, percentRadio18, and percentRadio20, call the addEventListener() method to register a listener with an event. 5. Look at line 27, subtotal.addEventListener("change", this).
When you call addEventListener(), you must pass it two parameters. The first is a string indicating the name of the event that is broadcast—in this case, "change". The second is a reference to either an object or a function that handles the event. In this case, the parameter is the keyword this, which refers to an instance of the class file (an object). Flash then looks on the object for a function with the name of the event. 6. Look at line 63, public function change(event:Object):Void.
This is the function that executes when the subtotal TextInput instance changes. 7. Select the TipCalculator.fla and select Control > Test Movie to test the file.
Using the handleEvent callback function You can also use listener objects that support a handleEvent function. Regardless of the name of the event that is broadcast, the listener object’s handleEvent method is called. You must use an if else or a switch statement to handle multiple events. For example, the following code uses an if else statement to handle the click and change events: // define the handleEvent function // pass it evt as the event object parameter
Using listeners to handle events
59
function handleEvent(evt){ // check if the event was a click if (evt.type == "click"){ // do something if the event was click } else if (evt.type == "change"){ // do something else if the event was change } }; // // // //
register the listener object to two different component instances because the function is defined on "this" object, the listener is this.
Using listener functions Unlike the handleEvent syntax, several listener functions can handle different events. So instead of having the if and else if checks in myHandler, you can just define myChangeHandler for the change event and myScrollHandler for the scroll event and register them, as shown here: myList.addEventListener("change", myChangeHandler); myList.addEventListener("scroll", myScrollHandler);
To use a listener function, you must first define a function: function myFunction:Function(evtObj:Object){ // your code here } Tip: The evtObj parameter is an object that is automatically generated when an event is triggered and passed to the function. The event object has properties that contain information about the event. For details, see “About the event object” on page 66.
Then you call the addEventListener() method from the component instance that broadcasts the event. The addEventListener() method takes two parameters: a string indicating the name of the event and a reference to the function. componentInstance.addEventListener("eventName", myFunction);
You can call addEventListener() from any component instance; it is mixed in to every component from the EventDispatcher class. For more information, see EventDispatcher.addEventListener() on page 416. For information about the events a component broadcasts, see each component’s entry in Chapter 6, “Components Dictionary,” on page 91. To register a listener object in a Flash (FLA) file:
1. In Flash, select File > New and create a new Flash document. 2. Drag a List component to the Stage from the Components panel. 3. In the Property inspector, enter the instance name myList.
60
Chapter 4: Handling Component Events
4. Select Frame 1 in the Timeline. 5. Select Window > Development Panels > Actions. 6. In the Actions panel, enter the following code: // declare variables var myList:mx.controls.List; var myHandler:Function; // add items to the list myList.addItem("Bird"); myList.addItem("Dog"); myList.addItem("Fish"); myList.addItem("Cat"); myList.addItem("Ape"); myList.addItem("Monkey"); // define myHandler function function myHandler(eventObj:Object){ // use the eventObj parameter // to capture the event type if (eventObj.type == "change"){ trace("The list changed"); } else if (eventObj.type == "scroll"){ trace("The list was scrolled"); } } // Register the myHandler function with myList. // When an item is selected (triggers the change event) or the // list is scrolled, myHandler executes. myList.addEventListener("change", myHandler); myList.addEventListener("scroll", myHandler); Note: The type property of the event object, evt, is a reference to the event name.
7. Select Control > Test Movie; then select an item in the list and scroll the list to see the results
in the Output panel. Caution: In a listener function, the keyword this refers to the component instance that calls addEventListener(), not to the Timeline or the class where the function is defined. However, you can use the Delegate class to delegate the listener function to a different scope. See “Delegating events” on page 63. To see an example of function scoping, see the next section.
About scope in listeners Scope refers to the object within which a function executes. Any variable references within that function are looked up as properties of that object. You can use the Delegate class to specify the scope of a listener. For more information, see “Delegating events” on page 63.
Using listeners to handle events
61
As discussed earlier, you register a listener with a component instance by calling addEventListener(). This method takes two parameters: a string indicating the name of the event, and a reference to either an object or a function. The following table lists the scope of each parameter type: Listener type
Scope
Object
Listener object
Function
Component instance broadcasting the event
If you pass addEventListener() an object, the callback function assigned to that object (or the function defined on that object) is invoked in the scope of the object. This means that the keyword this, when used inside the callback function, refers to the listener object, as follows: var lo:Object = new Object(); lo.click = function(evt){ // this refers to the object lo trace(this); } myButton.addEventListener("click", lo);
However, if you pass addEventListener() a function, the function is invoked in the scope of the component instance that calls addEventListener(). This means that the keyword this, when used inside the function, refers to the broadcasting component instance. This causes a problem if you’re defining the function in a class file. You cannot access the properties and methods of the class file with the expected paths because this doesn’t point to an instance of the class. To work around this problem, use the Delegate class to delegate a function to the correct scope. See “Delegating events” on page 63. The following code illustrates the scoping of a function when passed to addEventListener() in a class file. To use this code, copy it into an ActionScript (AS) file named Cart.as. Create a Flash (FLA) file with a Button component, myButton, and a DataGrid component, myGrid. Select both components on the Stage and press F8 to convert them into a new symbol named Cart. In the Linkage properties for the Cart symbol, assign it the class Cart. class Cart extends MovieClip { var myButton:mx.controls.Button; var myGrid:mx.controls.DataGrid; function myHandler(eventObj:Object){ // Use the eventObj parameter // to capture the event type. if (eventObj.type == "click"){ /* Send the value of this to the Output panel. Because myHandler is a function that is not defined on a listener object, this is a reference to the component instance to which myHandler is registered (myButton). Also, since this doesn't reference an instance of the Cart class, myGrid is undefined. */
62
Chapter 4: Handling Component Events
trace("this: " + this); trace("myGrid: " + myGrid); } } // register the myHandler function with myButton // when the button is clicked, myHandler executes function onLoad():Void{ myButton.addEventListener("click", myHandler); } }
Delegating events You can import the Delegate class into your scripts or classes to delegate events to specific scopes and functions. Use the following syntax: import mx.utils.Delegate; compInstance.addEventListener("eventName", Delegate.create(scopeObject, function));
The scopeObject parameter specifies the scope in which the specified function parameter is called. There are two common uses for calling Delegate.create():
• To dispatch the same event to two different functions. See the next section.
• To call functions within the scope of the containing class. When you pass a function as a parameter to addEventListener(), the function is invoked in the scope of the broadcaster component instance, not the object in which it is declared. See “Delegating the scope of a function” on page 65. Delegating events to functions Calling Delegate.create() is useful if you have two components that broadcast events of the same name. For example, if you have a check box and a button, you would have to use the switch statement on the information you get from the eventObject.target property in order to determine which component is broadcasting the click event. To use the following code, place a check box named myCheckBox_chb and a button named on the Stage. Select both instances and press F8 to create a new symbol. Click Advanced, Export for ActionScript, and enter the AS 2.0 class name Cart. You can give the new symbol any instance name you want in the Property inspector. The symbol is now an instance of the Cart class.
myButton_btn
import mx.utils.Delegate; import mx.controls.Button; import mx.controls.CheckBox; class Cart { var myCheckBox_chb:CheckBox;
Delegating events
63
var myButton_btn:Button; function onLoad() { myCheckBox_chb.addEventListener("click", this); myButton_btn.addEventListener("click", this); } function click(eventObj:Object) { switch(eventObj.target) { case myButton_btn: // sends the broadcaster instance name // and the event type to the Output panel trace(eventObj.target + ": " + eventObj.type); break; case myCheckBox_chb: trace(eventObj.target + ": " + eventObj.type); break; } } }
The following is the same class file (Cart.as) modified to use Delegate: import mx.utils.Delegate; import mx.controls.Button; import mx.controls.CheckBox; class Cart { var myCheckBox_chb:CheckBox; var myButton_btn:Button; function onLoad() { myCheckBox_chb.addEventListener("click", Delegate.create(this, chb_onClick)); myButton_btn.addEventListener("click", Delegate.create(this, btn_onClick)); } // two separate functions handle the events function chb_onClick(eventObj:Object) { // sends the broadcaster instance name // and the event type to the Output panel trace(eventObj.target + ": " + eventObj.type); // sends the absolute path of the symbol // that you associated with the Cart class // in the FLA file to the Output panel trace(this) } function btn_onClick(eventObj:Object) { trace(eventObj.target + ": " + eventObj.type); } }
64
Chapter 4: Handling Component Events
Delegating the scope of a function The addEventListener() method requires two parameters: the name of an event and a reference to a listener. The listener can either be an object or a function. If you pass an object, the callback function assigned to the object is invoked in the scope of the object. However, if you pass a function, the function is invoked in the scope of the component instance that calls addEventListener(). (For more information, see “About scope in listeners” on page 61.) Because the function is invoked in the scope of the broadcaster instance, the keyword this in the body of the function points to the broadcaster instance, not to the class that contains the function. Therefore, you cannot access the properties and methods of the class that contains the function. Use the Delegate class to delegate the scope of a function to the containing class so that you can access the properties and methods of the containing class. The following example uses the same approach as the previous section with a variation of the Cart.as class file: import mx.controls.Button; import mx.controls.CheckBox; class Cart { var myCheckBox_chb:CheckBox; var myButton_btn:Button; // define a variable to access // from the chb_onClick function var i:Number = 10 function onLoad() { myCheckBox_chb.addEventListener("click", chb_onClick); } function chb_onClick(eventObj:Object) { // You would expect to be able to access // the i variable and output 10. // However, this sends undefined // to the Output panel because // the function isn't scoped to // the Cart instance where i is defined. trace(i); } }
To access the properties and methods of the Cart class, call Delegate.create() as the second parameter of addEventListener(), as follows: import mx.utils.Delegate; import mx.controls.Button; import mx.controls.CheckBox; class Cart { var myCheckBox_chb:CheckBox; var myButton_btn:Button; // define a variable to access
Delegating events
65
// from the chb_onClick function var i:Number = 10 function onLoad() { myCheckBox_chb.addEventListener("click", Delegate.create(this, chb_onClick)); } function chb_onClick(eventObj:Object) { // Sends 10 to the Output panel // because the function is scoped to // the Cart instance trace(i); } }
About the event object The event object is an instance of the ActionScript Object class; it has the following properties that contain information about an event. Property
Description
type
A string indicating the name of the event.
target
A reference to the component instance broadcasting the event.
When an event has additional properties, they are listed in the event’s entry in the Components Dictionary. The event object is automatically generated when an event is triggered and passed to the listener object’s callback function or the listener function. You can use the event object inside the function to access the name of the event that was broadcast, or the instance name of the component that broadcast the event. From the instance name, you can access other component properties. For example, the following code uses the target property of the evtObj event object to access the label property of the myButton instance and sends the value to the Output panel: var myButton:mx.controls.Button; var listener:Object; listener = new Object(); listener.click = function(evtObj){ trace("The " + evtObj.target.label + " button was clicked"); } myButton.addEventListener("click", listener);
66
Chapter 4: Handling Component Events
CHAPTER 5 Customizing Components
You might want to change the appearance of components as you use them in different applications. There are three ways to accomplish this in Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004:
• Use the setStyle() method of each component and style declaration to change the color and text formatting of a component. See “Using styles to customize component color and text” on page 67.
• Apply a theme—a collection of styles and skins that make up a component’s appearance. See “About themes” on page 77.
• Modify or replace a component’s skins. Skins are symbols used to display components. Skinning is the process of changing the appearance of a component by modifying or replacing its source graphics. A skin can be a small piece, like a border’s edge or corner, or a composite piece like the entire picture of a button in its up state (the state in which it hasn’t been pressed). A skin can also be a symbol without a graphic, which contains code that draws a piece of the component. See “About skinning components” on page 80.
Using styles to customize component color and text Every component instance has style properties (also called styles) and setStyle() and getStyle() methods that you can use to set and get style property values. The setStyle() and getStyle() methods are inherited from the UIObject class. (For more information, see UIObject.setStyle() on page 825 and UIObject.getStyle() on page 814.) Note: You cannot set styles for the Media components.
The styles used by each component depend partially on what theme the document uses (see “About themes” on page 77). Some styles, such as defaultIcon, are used by the associated components regardless of the theme applied to the document. Other styles, such as themeColor and symbolBackgroundColor, are used only by components if the corresponding theme is in use. For example, themeColor is used only if the Halo theme is in use, and symbolBackgroundColor is used only if the Sample theme is in use.
67
You can use styles to customize a component in the following ways:
• Set styles on a component instance. You can change color and text properties of a single component instance. This is effective in some situations, but it can be time consuming if you need to set individual properties on all the components in a document. See “Setting styles on a component instance” on page 69.
• Create custom style declarations and apply them to several component instances. You may want to have groups of components in a document share a style. To do this, you can create custom style declarations to apply to the components you specify. See “Setting custom styles for groups of components” on page 69.
• Create default class style declarations. You can define a default class style declaration so that every instance of a class shares a default appearance. See “Setting styles for a component class” on page 71.
• Use inheriting styles to set styles for components in a portion of a document. The values of style properties set on containers are inherited by contained components. See “Setting inheriting styles on a container” on page 71.
• Use the global style declaration that sets styles for all components in a document. If you want to apply a consistent look to an entire document, you can create styles on the global style declaration. See “Setting global styles” on page 73. Flash does not display changes made to style properties when you view components on the Stage using the Live Preview feature. For more information, see “Components in Live Preview” on page 52. Supported styles Flash MX 2004 and Flash MX Professional 2004 provide many styles for customizing component color, text, and behavior. The set of styles used depends on each component and the theme applied to the document. For a list of styles supported by each component, see Chapter 6, “Components Dictionary,” on page 91. Flash provides two visual themes for components: Halo (HaloTheme.fla) and Sample (SampleTheme.fla). A theme is a set of styles and graphics that controls the appearance of components in a document. Each theme provides additional styles to the components. To know what style properties you can set for a component, you must know what theme is assigned to that component. The style tables for each component in the Components Dictionary indicate whether each style property applies to one or both of the supplied themes. (For more information, see “About themes” on page 77.)
68
Chapter 5: Customizing Components
Setting styles on a component instance You can write ActionScript code to set and get style properties on any component instance. The UIObject.setStyle() and UIObject.getStyle() methods can be called directly from any component. The following syntax specifies a property and value for a component instance: instanceName.setStyle("propertyName", value);
For example, the following code sets the accent colors on a Button instance called myButton that uses the Halo theme: myButton.setStyle("themeColor", "haloBlue"); Note: If the value is a string, it must be enclosed in quotation marks.
Even though you can access the styles directly as properties (for example, myButton.color = 0xFF00FF), it’s best to use the setStyle() and getStyle() methods so that the styles work correctly and components are redrawn with the new style settings. For more information, see UIObject.setStyle() on page 825. Style properties set on a component instance through setStyle() have the highest priority and override all other style settings discussed in the following sections. Note: If you want to change multiple properties, or change properties for multiple component instances, you should create a custom style. For more information, see “Setting custom styles for groups of components” on page 69. To set or change a property for a single component instance that uses the Halo theme:
1. Select the component instance on the Stage. 2. In the Property inspector, give it the instance name myComponent. 3. Open the Actions panel and select Scene 1, then select Layer 1: Frame 1. 4. Enter the following code to change the instance to orange: myComponent.setStyle("themeColor", "haloOrange");
5. Select Control > Test Movie to view the changes.
For a list of styles supported by a particular component, see the component’s entry in Chapter 6, “Components Dictionary,” on page 91. Setting custom styles for groups of components You can create custom style declarations to specify a unique set of properties for groups of components in your Flash document. You create a new instance of the CSSStyleDeclaration object, create a custom style name and place it on the _global.styles list (_global.styles.newStyle), specify the properties and values for the style, and assign the style name to component instances that should share the same look. To make changes to a custom style format, use the following syntax: _global.styles.CustomStyleName.setStyle(propertyName, propertyValue);
The CSSStyleDeclaration object is accessible if you have placed at least one component instance on the Stage.
Using styles to customize component color and text
69
Custom style settings have priority over class, inherited, and global style settings. For a list of the styles that each component supports, see the component entries in Chapter 6, “Components Dictionary,” on page 91. To create a custom style declaration for a group of components:
1. Make sure the document contains at least one component instance.
For more information, see “Adding components to Flash documents” on page 44. This example uses three button components with the instance names a, b, and c. If you use different components, give them instance names in the Property inspector and use those instance names in step 9. 2. Create a new layer in the Timeline and give it a name. 3. Select a frame in the new layer on which (or before which) the component appears. 4. Open the Actions panel. 5. Use the following syntax to create an instance of the CSSStyleDeclaration object to define the
new custom style format: var styleObj = new mx.styles.CSSStyleDeclaration();
6. Set the styleName property of the style declaration to name the style: styleObj.styleName = "newStyle";
7. Place the style on the _global.styles list: _global.styles.newStyle = styleObj;
You can also create a CSSStyleDeclaration object and assign it to a new style declaration by using the following syntax: var styleObj = _global.styles.newStyle = new mx.styles.CSSStyleDeclaration();
8. Use the following syntax to specify the properties you want to define for the newStyle
9. In the same Script pane, use the following syntax to set the styleName property of three specific
components to the custom style declaration: a.setStyle("styleName", "newStyle"); b.setStyle("styleName", "newStyle"); c.setStyle("styleName", "newStyle");
Now you can access styles on the custom style declaration using the setStyle() and getStyle() methods through its global styleName property. The following code sets the backgroundColor style on the newStyle style declaration: _global.styles.newStyle.setStyle("themeColor", "haloOrange");
70
Chapter 5: Customizing Components
Another option in setting custom style declarations is you can assign the CSSStyleDeclaration instance directly to the component instance’s styleName property and bypass storing the declaration in _global.styles. To use this approach, modify the above procedure as follows:
• Remove the ActionScript from steps 6 and 7 above. • Modify the ActionScript in step 9 to assign the CSSStyleDeclaration instance directly to the component instances: a.setStyle("styleName", styleObj); b.setStyle("styleName", styleObj); c.setStyle("styleName", styleObj);
Setting styles for a component class You can define a class style declaration for any class of component (Button, CheckBox, and so on) that sets default styles for each instance of that class. You must create the style declaration before you create the instances. Some components, such as TextArea and TextInput, have class style declarations predefined by default because their borderStyle and backgroundColor properties must be customized. Caution: If you replace a class style sheet, make sure to add any styles that you want from the old style sheet; otherwise, they will be overwritten.
The following code creates a class style declaration for CheckBox and sets the color for all check box instances to blue: if (_global.styles.CheckBox == undefined) { _global.styles.CheckBox = new mx.styles.CSSStyleDeclaration(); } _global.styles.CheckBox.setStyle(“color”, 0x0000FF);
Custom style settings have priority over inherited and global style settings. Setting inheriting styles on a container An inheriting style is a style that inherits its value from parent components in the document’s MovieClip hierarchy. If a text or color style is not set at an instance, custom, or class level, Flash searches the MovieClip hierarchy for the style value. Thus, if you set styles on a container component, the contained components inherit these style settings. The following styles are inheriting styles:
• fontFamily • fontSize • fontStyle • fontWeight • textAlign • textIndent • All single-value color styles (for example, themeColor is an inheriting style, but alternatingRowColors
is not)
Using styles to customize component color and text
71
The Style Manager tells Flash whether a style inherits its value. Additional styles can also be added at runtime as inheriting styles. For more information, see “StyleManager class” on page 721. Note: The CSS inherit value is not supported.
Inherited styles take priority over global styles. The following example demonstrates how inheriting styles can be used with an Accordion component, which is available with Flash MX Professional. (The inheriting styles feature is supported by both Flash MX and Flash MX Professional.) To create an Accordion component with styles that are inherited by the components in the individual Accordion panes:
1. Open a new FLA file. 2. Drag an Accordion component from the Components panel to the Stage. 3. Use the Property inspector to name and size the Accordion component. For this example, give
the component the instance name accordion. 4. Drag a TextInput component and a Button component from the Components panel to the
Stage. Select the instances on the Stage and delete them. By dragging the components to the Stage and immediately deleting them, you add the components to the library and make them available to your document at runtime. 5. Add the following ActionScript to the frame: var section1 = accordion.createChild(mx.core.View, "section1", {label: "First Section"}); var section2 = accordion.createChild(mx.core.View, "section2", {label: "Second Section"}); var input1 = section1.createChild(mx.controls.TextInput, "input1"); var button1 = section1.createChild(mx.controls.Button, "button1"); input1.text = "Text Input"; button1.label = "Button"; button1.move(0, input1.height + 10); var input2 = section2.createChild(mx.controls.TextInput, "input2"); var button2 = section2.createChild(mx.controls.Button, "button2"); input2.text = "Text Input"; button2.label = "Button"; button2.move(0, input2.height + 10);
The above code adds two children to the Accordion component and loads each with a TextInput and Button control, which this example uses to demonstrate style inheritance. 6. Select Control > Test Movie to see the document before adding style inheritance. 7. Add the following ActionScript to the end of the frame: accordion.setStyle("fontStyle", "italic");
8. Select Control > Test Movie to see the changes.
72
Chapter 5: Customizing Components
Notice that the fontStyle setting on the Accordion component affects not only the Accordion text itself but also the text associated with the TextInput and Button components inside the Accordion component. Setting global styles The global style declaration is assigned to all Flash components built with version 2 of the Macromedia Component Architecture. The _global object has a style property (_global.style) that is an instance of CSSStyleDeclaration. This property acts as the global style declaration. If you change a property’s value on the global style declaration, the change is applied to all components in your Flash document. Caution: Some styles are set on a component class’s CSSStyleDeclaration instance (for example, the backgroundColor style of the TextArea and TextInput components). Because the class style declaration takes precedence over the global style declaration when style values are determined, setting backgroundColor on the global style declaration would have no effect on TextArea and TextInput components. For more information, see “Using global, custom, and class styles in the same document” on page 73. To change one or more properties in the global style declaration:
1. Make sure the document contains at least one component instance.
For more information, see “Adding components to Flash documents” on page 44. 2. Select a frame in the Timeline on which (or before which) the components appear. 3. In the Actions panel, use code like the following to change properties on the global style
declaration. You need to list only the properties whose values you want to change, as shown here: _global.style.setStyle("color", 0xCC6699); _global.style.setStyle("themeColor", "haloBlue") _global.style.setStyle("fontSize",16); _global.style.setStyle("fontFamily" , "_serif");
4. Select Control > Test Movie to see the changes.
Using global, custom, and class styles in the same document If you define a style in only one place in a document, Flash uses that definition when it needs to know a property’s value. However, one Flash document can have a variety of style settings—style properties set directly on component instances, custom style declarations, default class style declarations, inheriting styles, and a global style declaration. In such a situation, Flash determines the value of a property by looking for its definition in all these places in a specific order. Flash looks for styles in the following order until a value is found: 1. Flash looks for a style property on the component instance. 2. Flash looks at the styleName property of the instance to see if a custom style declaration is
assigned to it. 3. Flash looks for the property on a default class style declaration.
Using styles to customize component color and text
73
4. If the style is one of the inheriting styles, Flash looks through the parent hierarchy for an
inherited value. 5. Flash looks for the style in the global style declaration. 6. If the property is still not defined, the property has the value undefined.
About color style properties Color style properties behave differently than noncolor properties. All color properties have a name that ends in “Color”—for example, backgroundColor, disabledColor, and color. When color style properties are changed, the color is immediately changed on the instance and in all of the appropriate child instances. All other style property changes simply mark the object as needing to be redrawn, and changes don’t occur until the next frame. The value of a color style property can be a number, a string, or an object. If it is a number, it represents the RGB value of the color as a hexadecimal number (0xRRGGBB). If the value is a string, it must be a color name. Color names are strings that map to commonly used colors. You can add new color names by using the Style Manager (see “StyleManager class” on page 721). The following table lists the default color names: Color name
Value
black
0x000000
white
0xFFFFFF
red
0xFF0000
green
0x00FF00
blue
0x0000FF
magenta
0xFF00FF
yellow
0xFFFF00
cyan
0x00FFFF
haloGreen
0x80FF4D
haloBlue
0x2BF5F5
haloOrange
0xFFC200
Note: If the color name is not defined, the component may not draw correctly.
You can use any valid ActionScript identifier to create your own color names (for example, "WindowText" or "ButtonText"). Use the Style Manager to define new colors, as shown here: mx.styles.StyleManager.registerColorName("special_blue", 0x0066ff);
Most components cannot handle an object as a color style property value. However, certain components can handle color objects that represent gradients or other color combinations. For more information, see the “Using styles” section of each component’s entry in Chapter 6, “Components Dictionary.”
74
Chapter 5: Customizing Components
You can use class style declarations and color names to easily control the colors of text and symbols on the screen. For example, if you want to provide a display configuration screen that looks like Microsoft Windows, you would define color names like ButtonText and WindowText and class style declarations like Button, CheckBox, and Window. Note: Some components provide style properties that are an array of colors, such as alternatingRowColors. You must set these styles only as an array of numeric RGB values, not color names.
Customizing component animations Several components, such as the Accordion, ComboBox, and Tree components, provide animation to demonstrate the transition between component states—for example, when switching between Accordion children, expanding the ComboBox drop-down list, and expanding or collapsing Tree folders. Additionally, components provide animation related to the selection and deselection of an item, such as rows in a list. You can control aspects of these animations through the following styles: Animation style
Description
openDuration
The duration of the transition for open easing in Accordion, ComboBox, and Tree components, in milliseconds. The default value is 250.
openEasing
A reference to a tweening function that controls the state animation in the Accordion, ComboBox, and Tree components. The default equation uses a sine in/out formula.
popupDuration
The duration of the transition as a menu opens in the Menu component, in milliseconds. The default value is 150. Note, however, that the animation always uses the default sine in/out equation.
selectionDuration
The duration of the transition in ComboBox, DataGrid, List, and Tree components from a normal to selected state or back from selected to normal, in milliseconds. The default value is 200.
selectionEasing
A reference to a tweening function that controls the selection animation in ComboBox, DataGrid, List, and Tree components. This style applies only for the transition from a normal to a selected state. The default equation uses a sine in/out formula.
The mx.transtions.easing package provides six classes to control easing: Easing class
Description
Back
Extends beyond the transition range at one or both ends one time to provide a slight overflow effect.
Bounce
Provides a bouncing effect entirely within the transition range at one or both ends. The number of bounces is related to the duration: longer durations produce more bounces.
Elastic
Provides an elastic effect that falls outside the transition range at one or both ends. The amount of elasticity is unaffected by the duration.
Using styles to customize component color and text
75
Easing class
Description
None
Provides an equal movement from start to end with no effects, slowing, or speeding. This transition is also commonly referred to as a linear transition.
Regular
Provides for slower movement at one or both ends for a speeding-up effect, a slowing-down effect, or both.
Strong
Provides for much slower movement at one or both ends. This effect is similar to Regular but is more pronounced.
Each of the classes in the mx.transitions.easing package provides the following three easing methods: Easing method
Description
easeIn
Provides the easing effect at the beginning of the transition.
easeOut
Provides the easing effect at the end of the transition.
easeInOut
Provides the easing effect at the beginning and end of the transition.
Because the easing methods are static methods of the easing classes, you never need to instantiate the easing classes. The methods are used in calls to setStyle(), as in the following example. import mx.transitions.easing.*; trace("_global.styles.Accordion = " + _global.styles.Accordion); _global.styles.Accordion.setStyle("openDuration", 1500); _global.styles.Accordion.setStyle("openEasing", Bounce.easeOut); Note: The default equation used by all transitions is not available in the easing classes listed above. To specify that a component should use the default easing method after another easing method has been specified, call setStyle("openEasing", null).
Getting style property values To retrieve a style property value, use UIObject.getStyle(). Every component that is a subclass of UIObject (which includes all version 2 components except the Media components) inherits the getStyle() method. This means you can call getStyle() from any component instance, just as you can call setStyle() from any component instance. The following code gets the value of the themeColor style and assigns it to the variable oldStyle: var myCheckBox:mx.controls.CheckBox; var oldFontSize:Number oldFontSize = myCheckBox.getStyle("fontSize"); trace(oldFontSize);
76
Chapter 5: Customizing Components
About themes Themes are collections of styles and skins. The default theme for Flash MX 2004 and Flash MX Professional 2004 is called Halo (HaloTheme.fla). The Halo theme lets you provide a responsive, expressive experience for your users. Flash MX 2004 and Flash MX Professional 2004 include one additional theme, Sample (SampleTheme.fla). The Sample theme provides an example of how you can use more styles for customization. (The Halo theme does not use all styles included in the Sample theme.) The theme files are located in the following folders in a default installation:
• Macintosh: HD/Applications/Macromedia Flash MX 2004/Configuration/ComponentFLA/ You can create new themes and apply them to an application to change the look and feel of all the components. For example, you could create themes that mimic the native operating system appearance. Components use skins (graphic or movie clip symbols) to display their appearances. The AS file that defines each component contains code that loads specific skins for the component. You can easily create a new theme by making a copy of the Halo or Sample theme and altering the graphics in the skins. A theme can also contain a new set of style default values. You must write ActionScript code to create a global style declaration and any additional style declarations. For more information, see “Modifying default style property values in a theme” on page 78. Creating a new theme If you don’t want to use the Halo theme or the Sample theme, you can modify one of them to create a new theme. Some skins in the themes have a fixed size. You can make them larger or smaller and the components will automatically resize to match them. Other skins are composed of multiple pieces, some static and some that stretch. Some skins (for example, RectBorder and ButtonSkin) use the ActionScript drawing API to draw their graphics, because it is more efficient in terms of size and performance. You can use the ActionScript code in those skins as a template to adjust the skins to your needs. For a list of the skins supported by each component and their properties, see Chapter 6, “Components Dictionary,” on page 91. To create a new theme:
1. Select the theme FLA file that you want to use as a template, and make a copy.
Give the copy a unique name such as MyTheme.fla. 2. Select File > Open MyTheme.fla in Flash. 3. Select Window > Library to open the library if it isn’t open already.
About themes
77
4. Double-click any skin symbol you want to modify to open it in symbol-editing mode.
The skins are located in the Flash UI Components 2/Themes/MMDefault/Component Assets folder (this example uses RadioButton Assets). 5. Modify the symbol or delete the graphics and create new graphics.
You may need to select View > Zoom In to increase the magnification. When you edit a skin, you must maintain the registration point in order for the skin to be displayed correctly. The upper left corner of all edited symbols must be at (0,0). For example, open the States/RadioFalseDisabled asset and change the inner circle to a light gray. 6. When you finish editing the skin symbol, click the Back button at the left side of the
information bar at the top of the Stage to return to document-editing mode. 7. Repeat steps 4-6 until you’ve edited all the skins you want to change. 8. Apply MyTheme.fla to a document by following the steps shown later in this chapter. (See
“Applying a theme to a document” on page 79.) Modifying default style property values in a theme The default style property values are provided by each theme in a class named Default. To change the defaults for a custom theme, create a new ActionScript class called Default in a package appropriate for your theme, and change the default settings as desired. To modify default style values in a theme:
1. Create a new folder for your theme in First Run/Classes/mx/skins.
For example, create a folder called myTheme. 2. Copy an existing Defaults class to your new theme folder.
For example, copy mx/skins/halo/Defaults.as to mx/skins/myTheme/Defaults.as. 3. Open the new Defaults class in an ActionScript editor.
Flash MX 2004 Professional users can open the file within Flash MX 2004 Professional. Flash MX 2004 users can open the file in Notepad in Windows or SimpleText on the Macintosh. 4. Modify the class declaration to reflect the new package.
For example, our new class declaration is class mx.skins.myTheme.Defaults. 5. Modify the style settings as desired.
For example, change the default disabled color to a dark red. o.disabledColor = 0x663333;
6. Save the changed Defaults class file. 7. Copy an existing FocusRect class from the source theme to your custom theme.
For example, copy mx/skins/halo/FocusRect.as to mx/skins/myTheme/FocusRect.as. 8. Open the new FocusRect class in an ActionScript editor.
78
Chapter 5: Customizing Components
9. Modify all references to the source theme’s package to the new theme’s package.
For example, change all occurrences of “halo” to “myTheme”. 10. Save the changed FocusRect class file. 11. Open the FLA file for your custom theme.
This example uses MyTheme.fla. 12. Open the library (Window > Library) and locate the Defaults symbol.
In this example, it’s in Flash UI Components 2/Themes/MMDefault/Defaults. 13. Edit the symbol properties for the Default symbol. 14. Change the AS 2.0 Class setting to reflect your new package.
The example class is mx.skins.myTheme.Defaults. 15. Click OK. 16. Locate the FocusRect symbol.
In this example, it’s in Flash UI Components 2/Themes/MMDefault/FocusRect. 17. Edit the symbol properties for the FocusRect symbol. 18. Change the AS 2.0 Class setting to reflect your new package.
The example class is mx.skins.myTheme.FocusRect. 19. Click OK. 20. Apply the custom theme to a document by following the steps in the next section.
Remember to include the Defaults and FocusRect symbols when dragging assets from your custom theme to the target document. In this example you used a new theme to customize the text color of disabled components. This particular customization, changing a single default style property value, would have been accomplished more easily through styling as explained in “Using styles to customize component color and text” on page 67. Using a new theme to customize defaults is appropriate when customizing many style properties or when already creating a new theme to customize component graphics. Applying a theme to a document To apply a new theme to a document, open a theme FLA file as an external library, and drag the theme folder from the external library to the document library. The following steps explain the process in detail. To apply a theme to a document:
1. Select File > Open and open the document that uses version 2 components in Flash, or select
File > New and create a new document that uses version 2 components. 2. Select File > Save and choose a unique name such as ThemeApply.fla.
About themes
79
3. Select File > Import > Open External Library, and select the FLA file of the theme you want to
apply to your document. If you haven’t created a new theme, you can use the Sample theme. 4. In the theme’s Library panel, select Flash UI Components 2/Themes/MMDefault and drag the
Assets folder of any components in your document to the ThemeApply.fla library. For example, drag the RadioButton Assets folder to the ThemeApply.fla library. If you’re unsure about which components are in the document, drag the Sample Theme movie clip to the Stage. The skins are automatically assigned to components in the document. Note: The Live Preview of the components on the Stage will not reflect the new theme.
5. If you dragged individual component Assets folders to the ThemeApply.fla library, make sure
the Assets symbol for each component is set to Export in First Frame. For example, the Assets folder for the RadioButton component is called RadioButton Assets; it has a symbol called RadioButtonAssets, which contains all of the individual asset symbols. If you set Export in First Frame on the RadioButtonAssets symbol, all individual asset symbols will also export in the first frame. 6. Select Control > Test Movie to see the document with the new theme applied.
In this example, make sure you have a RadioButton instance on the Stage and set its enabled property to false in the Actions panel in order to see the new disabled RadioButton appearance.
About skinning components Skins are movie clip symbols a component uses to display its appearance. Most skins contain shapes that represent the component’s appearance. Some skins contain only ActionScript code that draws the component in the document. Version 2 components are compiled clips—you cannot see their assets in the library. However, the Flash installation includes FLA files that contain all the component skins. These FLA files are called themes. Each theme has a different appearance and behavior, but contains skins with the same symbol names and linkage identifiers. This lets you drag a theme onto the Stage in a document to change its appearance. You also use the theme FLA files to edit component skins. The skins are located in the Themes folder in the Library panel of each theme FLA file. (For more information about themes, see “About themes” on page 77.) Each component is composed of many skins. For example, the down arrow of the ScrollBar subcomponent consists of four skins: ScrollDownArrowDisabled, ScrollDownArrowDown, ScrollDownArrowOver, and ScrollDownArrowUp. The entire ScrollBar uses 13 different skin symbols. Some components share skins; for example, components that use scroll bars—such as ComboBox, List, and ScrollPane—share the skins in the ScrollBar Skins folder. You can edit existing skins and create new skins to change the appearance of components.
80
Chapter 5: Customizing Components
The AS file that defines each component class contains code that loads specific skins for the component. Each component skin corresponds to a skin property that is assigned to a skin symbol’s linkage identifier. For example, the pressed (down) state of the down arrow of the ScrollBar component has the skin property name downArrowDownName. The default value of the downArrowDownName property is "ScrollDownArrowDown", which is the linkage identifier of the skin symbol in the theme FLA file. You can edit existing skins and apply them to all components that use the skin by editing the skin symbol and leaving the existing linkage identifier. You can create new skins and apply them to specific component instances by setting the skin properties for a component instance. You do not need to edit the component’s AS file to change its skin properties; you can pass skin property values to the component’s constructor function when the component is created in your document. The skin properties for each component are listed in each component’s entry in the Components Dictionary. For example, the skin properties for the Button component are located here: Components Dictionary > Button component > Customizing the Button component > Using skins with the Button component. Choose one of the following ways to skin a component according to what you want to do. These approaches are listed from easiest to most difficult.
• To change the skins associated with all instances of a particular component in a single document, copy and modify individual skin elements. (See “Editing component skins in a document” on page 81). This method of skinning is recommended for beginners, because it doesn’t require any scripting.
• To replace all the skins in a document with a new set (with each kind of component sharing the same appearance), apply a theme. (See “About themes” on page 77.) This method of skinning is recommended for applying a consistent look and feel across all components and across several documents.
• To link the color of a skin element to a style property, add ActionScript code to the skin to register it as a colored skin element. (See “Linking skin color to styles” on page 83).
• To use different skins for multiple instances of the same component, create new skins and set skin properties. (See “Creating new component skins” on page 83 and “Applying new skins to a component” on page 85.)
• To change skins in a subcomponent (such as a scroll bar in a List component), subclass the component. (See “Applying new skins to a subcomponent” on page 86.)
• To change skins of a subcomponent that aren’t directly accessible from the main component (such as a List component in a ComboBox component), replace skin properties in the prototype. (See “Changing skin properties in the prototype” on page 89.) Editing component skins in a document To edit the skins associated with all instances of a particular component in a single document, copy the skin symbols from the theme to the document and edit the graphics as desired.
About skinning components
81
The procedure described below is very similar to creating and applying a new theme (see “About themes” on page 77). The primary difference is that this procedure describes copying symbols directly from the theme already in use to a single document and editing only a small number of all skins available. This is appropriate when your modifications are all in a single document and when you are modifying skins for only a few components. If the edited skins will be shared in multiple documents or encompass changes in several components, you may find it maintenance to be easier if you create a new theme. To edit component skins in a document:
1. If you already applied the Sample theme to a document, skip to step 5. 2. Select File > Import > Open External Library, and select the HaloTheme.fla file.
This file is located in the application-level configuration folder. For the exact location on your operating system, see “About themes” on page 77. 3. In the theme’s Library panel, select Flash UI Components 2/Themes/MMDefault and drag the
Assets folder of any components in your document to the library for your document. For example, drag the RadioButton Assets folder to the ThemeApply.fla library. 4. If you dragged individual component Assets folders to the library, make sure the Assets symbol
for each component is set to Export in First Frame. For example, the Assets folder for the RadioButton component is called RadioButton Assets; it has a symbol called RadioButtonAssets, which contains all of the individual asset symbols. If you set Export in First Frame on the RadioButtonAssets symbol, all individual asset symbols will also export in the first frame. 5. Double-click any skin symbol you want to modify to open it in symbol-editing mode.
For example, open the States/RadioFalseDisabled symbol. 6. Modify the symbol or delete the graphics and create new graphics.
You may need to select View > Zoom In to increase the magnification. When you edit a skin, you must maintain the registration point in order for the skin to be displayed correctly. The upper left corner of all edited symbols must be at (0,0). For example, change the inner circle to a light gray. 7. When you finish editing the skin symbol, click the Back button at the left side of the
information bar at the top of the Stage to return to document-editing mode. 8. Repeat steps 5-7 until you’ve edited all the skins you want to change. Note: The live preview of the components on the Stage will not reflect the edited skins.
9. Select Control > Test Movie.
In this example, make sure you have a RadioButton instance on the Stage and set its enabled property to false in the Actions panel in order to see the new disabled RadioButton appearance.
82
Chapter 5: Customizing Components
Creating new component skins If you want to use a particular skin for one instance of a component, but another skin for another instance of the component, you must open a theme FLA file and create a new skin symbol. Components are designed to make it easy to use different skins for different instances. To create a new skin:
1. Select File > Open and open the theme FLA file that you want to use as a template. 2. Select File > Save As and select a unique name, such as MyTheme.fla. 3. Select the skins that you want to edit (in this example, RadioTrueUp).
The skins are located in the Themes/MMDefault/Component Assets folder (in this example, Themes/MMDefault/RadioButton Assets/States). 4. Select Duplicate from the Library options menu (or by right-clicking the symbol), and give the
symbol a unique name, such as MyRadioTrueUp. 5. Click Advanced in the Symbol Properties dialog box, and select Export for ActionScript.
A linkage identifier that matches the symbol name is entered automatically. 6. Double-click the new skin in the library to open it in symbol-editing mode. 7. Modify the movie clip, or delete it and create a new one.
You may need to select View > Zoom In to increase the magnification. When you edit a skin, you must maintain the registration point in order for the skin to be displayed correctly. The upper left corner of all edited symbols must be at (0,0). 8. When you finish editing the skin symbol, click the Back button at the left side of the
information bar at the top of the Stage to return to document-editing mode. 9. Select File > Save but don’t close MyTheme.fla. Now you must create a new document in which
to apply the edited skin to a component. For more information, see “Applying new skins to a component” on page 85, “Applying new skins to a subcomponent” on page 86, or “Changing skin properties in the prototype” on page 89. Note: Flash does not display changes made to component skins when you view components on the Stage using Live Preview.
Linking skin color to styles The version 2 component framework makes it easy to link a visual asset in a skin element to a style set on the component using the skin. To register a movie clip instance to a style, or an entire skin element to a style, add ActionScript code in the Timeline of the skin to call mx.skins.ColoredSkinElement.setColorStyle(targetMovieClip, styleName).
About skinning components
83
To link a skin to a style property:
1. If you already applied the Sample theme to a document, skip to step 5. 2. Select File > Import > Open External Library, and select the HaloTheme.fla file.
This file is located in the application-level configuration folder. For the exact location on your operating system, see “About themes” on page 77. 3. In the theme’s Library panel, select Flash UI Components 2/Themes/MMDefault, and drag the
Assets folder of any components in your document to the library for your document. For example, drag the RadioButton Assets folder to the target library. 4. If you dragged individual component assets folders to the library, make sure the Assets symbol
for each component is set to Export in First Frame. For example, the Assets folder for the RadioButton component is called RadioButton Assets; it has a symbol called RadioButtonAssets, which contains all of the individual asset symbols. If you set Export in First Frame on the RadioButtonAssets symbol, all individual asset symbols will also export in the first frame. 5. Double-click any skin symbol you want to modify to open it in symbol-editing mode.
For example, open the States/RadioFalseDisabled symbol. 6. If the element to be colored is a graphic symbol and not a movie clip instance, use Modify >
Convert to Symbol to covert it to a movie clip instance. For this example, change the center graphic, which is an instance of the graphic symbol RadioShape1, to a movie clip symbol; then name it Inner Circle. You do not need to select Export for ActionScript. It would be good practice, but it is not required, to move the newly created movie clip symbol to the Elements folder of the component assets being edited. 7. If you converted a graphic symbol to a movie clip instance in the previous step, give that
instance a name so it can be targeted in ActionScript. For this example, name the instance innerCircle. 8. Add ActionScript code to register the skin element or a movie clip instance it contains as a
colored skin element. For example, add the following code to the skin element’s Timeline. mx.skins.ColoredSkinElement.setColorStyle(innerCircle, "symbolBackgroundDisabledColor");
In this example you’re using a color that already corresponds to an existing style name in the Sample style. Wherever possible, it’s best to use style names corresponding to official Cascading Style Sheet standards or styles provided by the Halo and Sample themes. 9. Repeat steps 5-8 until you’ve edited all the skins you want to change.
For this example, repeat these steps for the RadioTrueDisabled skin, but instead of converting the existing graphic to a movie clip, delete the graphic and drag the existing Inner Circle symbol to the RadioTrueDisabled skin element. 10. When you finish editing the skin symbol, click the Back button at the left side of the
information bar at the top of the Stage to return to document-editing mode.
84
Chapter 5: Customizing Components
11. Drag an instance of the component to the Stage.
For this example, drag two RadioButton components to the Stage, set one to selected, and use ActionScript to set both to disabled in order to see the changes. 12. Add ActionScript code to the document to set the new style property on the component
instances or at the global level. For this example, set the property at the global level as follows: _global.style.setStyle("symbolBackgroundDisabledColor", 0xD9D9D9);
13. Select Control > Test Movie.
Applying new skins to a component Once you have created a new skin, you must apply it to a component in a document. You can use the createClassObject() method to dynamically create the component instances, or you can manually place the component instances on the Stage. There are two different ways to apply skins to component instances, depending on how you add the components to a document. To dynamically create a component and apply a new skin:
1. Select File > New to create a new Flash document. 2. Select File > Save and give the file a unique name, such as DynamicSkinning.fla. 3. Drag any components from the Components panel to the Stage, including the component
whose skin you edited (in this example, RadioButton), and delete them. This adds the symbols to the document’s library, but doesn’t make them visible in the document. 4. Drag MyRadioTrueUp and any other symbols you customized from MyTheme.fla to the Stage
of DynamicSkinning.fla, and delete them. This adds the symbols to the document’s library, but doesn’t make them visible in the document. 5. Open the Actions panel and enter the following on Frame 1: import mx.controls.RadioButton; createClassObject(RadioButton, "myRadio", 0, {trueUpIcon:"MyRadioTrueUp", label: "My Radio Button"});
6. Select Control > Test Movie. To manually add a component to the Stage and apply a new skin:
1. Select File > New to create a new Flash document. 2. Select File > Save and give the file a unique name, such as ManualSkinning.fla. 3. Drag components from the Components panel to the Stage, including the component whose
skin you edited (in this example, RadioButton). 4. Drag MyRadioTrueUp and any other symbols you customized from MyTheme.fla to the Stage
of ManualSkinning.fla, and delete them. This adds the symbols to the document’s library, but doesn’t make them visible in the document.
About skinning components
85
5. Select the RadioButton component on the Stage and open the Actions panel. 6. Attach the following code to the RadioButton instance: onClipEvent(initialize){ trueUpIcon = "MyRadioTrueUp"; }
7. Select Control > Test Movie.
Applying new skins to a subcomponent In certain situations you may want to modify the skins of a subcomponent in a component, but the skin properties are not directly available (for example, there is no direct way to alter the skins of the scroll bar in a List component). The following code lets you access the scroll bar skins. All the scroll bars that are created after this code runs will also have the new skins. If a component is composed of subcomponents, the subcomponents are identified in the component’s entry in Chapter 6, “Components Dictionary.” To apply a new skin to a subcomponent:
1. Follow the steps in “Creating new component skins” on page 83, but edit a scroll bar skin.
For this example, edit the ScrollDownArrowDown skin and give it the new name MyScrollDownArrowDown. 2. Select File > New to create a new Flash document. 3. Select File > Save and give the file a unique name, such as SubcomponentProject.fla. 4. Double-click the List component in the Components panel to add it to the Stage, and press
Backspace to delete it from the Stage. This adds the component to the Library panel, but doesn’t make the component visible in the document. 5. Drag MyScrollDownArrowDown and any other symbols you edited from MyTheme.fla to the
Stage of SubcomponentProject.fla, and delete them. This adds the symbol to the Library panel, but doesn’t make it visible in the document. 6. Do one of the following: ■
If you want to change all scroll bars in a document, enter the following code in the Actions panel on Frame 1 of the Timeline: import mx.controls.List; import mx.controls.scrollClasses.ScrollBar; ScrollBar.prototype.downArrowDownName = "MyScrollDownArrowDown";
You can then enter the following code on Frame 1 to create a list dynamically: createClassObject(List, "myListBox", 0, {dataProvider: ["AL","AR","AZ", "CA","HI","ID", "KA","LA","MA"]});
Or, you can drag a List component from the library to the Stage.
86
Chapter 5: Customizing Components
■
If you want to change a specific scroll bar in a document, enter the following code in the Actions panel on Frame 1 of the Timeline: import mx.controls.List import mx.controls.scrollClasses.ScrollBar var oldName = ScrollBar.prototype.downArrowDownName; ScrollBar.prototype.downArrowDownName = "MyScrollDownArrowDown"; createClassObject(List, "myList1", 0, {dataProvider: ["AL","AR","AZ", "CA","HI","ID", "KA","LA","MA"]}); myList1.redraw(true); ScrollBar.prototype.downArrowDownName = oldName; Note: Set enough data so that the scroll bars appear, or set the vScrollPolicy property to true.
7. Select Control > Test Movie.
You can also set subcomponent skins for all components in a document by setting the skin property on the subcomponent’s prototype object in the #initclip section of a skin symbol. To use #initclip to apply an edited skin to all components in a document:
1. Follow the steps in “Creating new component skins” on page 83, but edit a scroll bar skin. For
this example, edit the ScrollDownArrowDown skin and give it the new name MyScrollDownArrowDown. 2. Select File > New and create a new Flash document. Save it with a unique name, such as
SkinsInitExample.fla. 3. Select the MyScrollDownArrowDown symbol from the library of the edited theme library
example, drag it to the Stage of SkinsInitExample.fla, and delete it. This adds the symbol to the library without making it visible on the Stage. 4. Select MyScrollDownArrowDown in the SkinsInitExample.fla library, and select Linkage from
the Library options menu. 5. Select the Export for ActionScript check box. Click OK.
Export in First Frame is automatically selected. 6. Double-click MyScrollDownArrowDown in the library to open it in symbol-editing mode. 7. Enter the following code on Frame 1 of the MyScrollDownArrowDown symbol: #initclip 10 import mx.controls.scrollClasses.ScrollBar; ScrollBar.prototype.downArrowDownName = "MyScrollDownArrowDown"; #endinitclip
8. Do one of the following to add a List component to the document: ■
■
Drag a List component from the Components panel to the Stage. Enter enough label parameters so that the vertical scroll bar will appear. Drag a List component from the Components panel to the Stage and delete it. Enter the following code on Frame 1 of the main Timeline of SkinsInitExample.fla: createClassObject(mx.controls.List, "myListBox1", 0, {dataProvider: ["AL","AR","AZ", "CA","HI","ID", "KA","LA","MA"]}); Note: Add enough data so that the vertical scroll bar appears, or set vScrollPolicy to true.
About skinning components
87
The following example explains how to skin something that’s already on the Stage. This example skins only List scroll bars; any TextArea or ScrollPane scroll bars would not be skinned. To use #initclip to apply an edited skin to specific components in a document:
1. Follow the steps in “Editing component skins in a document” on page 81, but edit a scroll bar
skin. For this example, edit the ScrollDownArrowDown skin and give it the new name MyScrollDownArrowDown. 2. Select File > New and create a Flash document. 3. Select File > Save and give the file a unique name, such as MyVScrollTest.fla. 4. Drag MyScrollDownArrowDown from the theme library to the MyVScrollTest.fla library. 5. Select Insert > New Symbol and give the symbol a unique name, such as MyVScrollBar. 6. Select the Export for ActionScript check box. Click OK.
Export in First Frame is automatically selected. 7. Enter the following code on Frame 1 of the MyVScrollBar symbol: #initclip 10 import MyVScrollBar Object.registerClass("VScrollBar", MyVScrollBar); #endinitclip
8. Drag a List component from the Components panel to the Stage. 9. In the Property inspector, enter as many Label parameters as necessary for the vertical scroll bar
to appear. 10. Select File > Save. 11. Select File > New and create a new ActionScript file. 12. Enter the following code: import mx.controls.VScrollBar import mx.controls.List class MyVScrollBar extends VScrollBar{ function init():Void{ if (_parent instanceof List){ downArrowDownName = "MyScrollDownArrowDown"; } super.init(); } }
13. Select File > Save and save this file as MyVScrollBar.as. 14. Click a blank area on the Stage and, in the Property inspector, click the Publish Settings button. 15. Click the ActionScript Version Settings button. 16. Click the Add New Path (+) button to add a new classpath, and select the Target button to
browse to the location of the MyVScrollBar.as file on your hard disk. 17. Select Control > Test Movie.
88
Chapter 5: Customizing Components
Changing skin properties in the prototype If a component does not directly support skin variables, you can subclass the component and replace its skins. For example, the ComboBox component doesn’t directly support skinning its drop-down list, because the ComboBox component uses a List component as its drop-down list. If a component is composed of subcomponents, the subcomponents are identified in the component’s entry in Chapter 6, “Components Dictionary.” To skin a subcomponent:
1. Follow the steps in “Editing component skins in a document” on page 81, but edit a scroll bar
skin. For this example, edit the ScrollDownArrowDown skin and give it the new name MyScrollDownArrowDown. 2. Select File > New and create a Flash document. 3. Select File > Save and give the file a unique name, such as MyComboTest.fla. 4. Drag MyScrollDownArrowDown from the theme library above to the Stage of
MyComboTest.fla, and delete it. This adds the symbol to the library, but doesn’t make it visible on the Stage. 5. Select Insert > New Symbol and give the symbol a unique name, such as MyComboBox. 6. Select the Export for ActionScript check box and click OK.
Export in First Frame is automatically selected. 7. Enter the following code in the Actions panel on Frame 1 of the MyComboBox symbol: #initclip 10 import MyComboBox Object.registerClass("ComboBox", MyComboBox); #endinitclip
8. When you finish editing the symbol, click the Back button at the left side of the information
bar at the top of the Stage to return to document-editing mode. 9. Drag a ComboBox component to the Stage. 10. In the Property inspector, enter as many Label parameters as necessary for the vertical scroll bar
to appear. 11. Select File > Save. 12. Select File > New and create a new ActionScript file.
About skinning components
89
13. Enter the following code: import mx.controls.ComboBox import mx.controls.scrollClasses.ScrollBar class MyComboBox extends ComboBox{ function getDropdown():Object{ var oldName = ScrollBar.prototype.downArrowDownName; ScrollBar.prototype.downArrowDownName = "MyScrollDownArrowDown"; var r = super.getDropdown(); ScrollBar.prototype.downArrowDownName = oldName; return r; } }
14. Select File > Save and save this file as MyComboBox.as. 15. Return to the file MyComboTest.fla. 16. Click a blank area on the Stage and, in the Property inspector, click the Publish Settings button. 17. Click the ActionScript Version Settings button. 18. Click the Add New Path (+) button to add a new classpath, and select the Target button to
browse to the location of the MyComboBox.as file on your hard disk. 19. Select Control > Test Movie.
90
Chapter 5: Customizing Components
CHAPTER 6 Components Dictionary
This reference chapter describes each component and its application programming interface (API). Each component description contains information about the following:
• • • • • • •
Keyboard interaction Live preview Accessibility Setting the component parameters Using the component in an application Customizing the component with styles and skins ActionScript methods, properties, and events
Components are presented alphabetically. You can also find components arranged by category in the tables that follow. This chapter contains the following sections: Types of components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Other listings in this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Types of components The following tables list the different components, arranged by category, in version 2 of the Macromedia Component Architecture. User interface (UI) components Component
Description
Accordion component (Flash Professional only)
A set of vertical overlapping views with buttons along the top that allow users to switch views.
Alert component (Flash Professional only)
A window that presents a message and buttons to capture the user’s response.
Button component
A resizable button that can be customized with a custom icon.
91
Component
Description
CheckBox component
Allows users to make a Boolean (true or false) choice.
ComboBox component
Allows users to select one option from a scrolling list of choices. This component can have an selectable text field at the top of the list that allows users to search the list.
DataGrid component (Flash Professional only)
Allows users to display and manipulate multiple columns of data.
DateChooser component (Flash Professional only)
Allows users to select one or more dates from a calendar.
DateField component (Flash Professional only)
An nonselectable text field with a calendar icon. When a user clicks inside the component’s bounding box, Macromedia Flash displays a DateChooser component.
Label component
A non-editable, single-line text field.
List component
Allows users to select one or more options from a scrolling list.
Loader component
A container that holds a loaded SWF or JPEG file.
Menu component (Flash Professional only)
A standard desktop application menu; allows users to select one command from a list.
MenuBar component (Flash Professional only)
A horizontal bar of menus.
NumericStepper component
A text box with clickable arrows that raise and lower the value of a number.
ProgressBar component
Displays the progress of a process, such as a loading operation.
RadioButton component
Allows users to select between mutually exclusive options.
ScrollPane component
Displays movies, bitmaps, and SWF files in a limited area using automatic scroll bars.
TextArea component
An optionally editable, multiline text field.
TextInput component
An optionally editable, single-line text input field.
Tree component (Flash Professional only)
Allows a user to manipulate hierarchical information.
Window component
A draggable window with a title bar, caption, border, and Close button and content-display area.
UIScrollBar component
Allows you to add a scroll bar to a text field.
Data handling
92
Component
Description
Data binding classes (Flash Professional only)
Classes that implement the Flash runtime data binding functionality.
DataHolder component (Flash Professional only)
Holds data and can be used as a connector between components.
Chapter 6: Components Dictionary
Component
Description
DataProvider API
The model for linear-access lists of data; it provides simple arraymanipulation capabilities that broadcast data changes.
DataSet component (Flash Professional only)
A building block for creating data-driven applications.
RDBMSResolver component (Flash Professional only)
Lets you save data back to any supported data source. This component translates the XML that can be received and parsed by a web service, JavaBean, servlet, or ASP page.
Web service classes (Flash Professional only)
Classes that allow access to web services that use Simple Object Access Protocol (SOAP). These classes are in the mx.services package.
Provides scriptless access to web service method calls. WebServiceConnector component (Flash Professional only) XMLConnector component (Flash Professional only)
POST methods.
Reads and writes XML documents by using the HTTP GET and
XUpdateResolver component (Flash Professional only)
Lets you save data back to any supported data source. This component translates the delta packet into XUpdate.
Media components Component
Description
MediaController component
Controls streaming media playback in an application.
MediaDisplay component
Displays streaming media in an application.
MediaPlayback component
A combination of the MediaDisplay and MediaController components.
For more information on these components, see “Media components (Flash Professional only)” on page 497. Managers Class
Description
DepthManager class
Manages the stacking depths of objects.
FocusManager class
Handles Tab key navigation between components. Also handles focus changes as users click in the application.
PopUpManager class
Lets you create and delete pop-up windows.
StyleManager class
Lets you register styles and manages inherited styles.
SystemManager class
Lets you manage which top-level window is activated.
Types of components
93
Screens Class
Description
Form class (Flash Professional Lets you manipulate form application screens at runtime. only) Screen class
Base class for the Slide and Form classes. See Screen class (Flash Professional only).
Slide class (Flash Professional only)
Lets you manipulate slide presentation screens at runtime.
Other listings in this chapter This chapter also describes several classes and APIs that don’t fall into the above categories of components. They are listed in the following table.
94
Item
Description
CellRenderer API
A set of properties and methods that the list-based components (List, DataGrid, Tree, Menu, and ComboBox) use to manipulate and display custom cell content for each of their rows.
Collection interface (Flash Professional only)
Lets you manage a group of related items, called collection items. Each collection item in this set has properties that are described in the metadata of the collection item class definition.
DataGridColumn class (Flash Professional only)
Lets you create objects to use as columns of a data grid.
Delegate class
Allows a function passed from one object to another to be run in the context of the first object.
Delta interface (Flash Professional only)
Provides access to the transfer object, collection, and transfer object-level changes.
DeltaItem class (Flash Professional only)
Provides information about an individual operation performed on a transfer object.
DeltaPacket interface (Flash Professional only)
Along with the Delta interface and DeltaItem class, lets you manage changes made to data.
EventDispatcher class
Let you add and remove event listeners so that your code can react to events appropriately.
Iterator interface (Flash Professional only)
Lets you step through the objects that a collection contains.
MenuDataProvider class
Lets XML instances assigned to a Menu.dataProvider property use methods and properties to manipulate their own data as well as the associated menu views.
RectBorder class
Describes the styles used to control component borders.
SimpleButton class
Lets you control some aspects of button appearance and behavior.
TransferObject interface
Defines a set of methods that items managed by the DataSet component must implement.
Chapter 6: Components Dictionary
Item
Description
TreeDataProvider interface (Flash Professional only)
Tree.dataProvider property.
A set of properties and methods used to create XML for the
UIComponent class
Provides methods, properties, and events that allow components to share some common behavior.
UIEventDispatcher class
Allows components to emit certain events. This class is mixed in to the UIComponent class.
UIObject class
The base class for all version 2 components.
Other listings in this chapter
95
CHAPTER 6 Components Dictionary
Accordion component (Flash Professional only)
The Accordion component is a navigator that contains a sequence of children that it displays one at a time. The children must be objects that inherit from the UIObject class (which includes all components and screens built with version 2 of the Macromedia Component Architecture); most often, children are a subclass of the View class. This includes movie clips assigned to the class mx.core.View. To maintain tabbing order in an accordion’s children, the children must also be instances of the View class. An accordion creates and manages header buttons that a user can click to navigate between the accordion’s children. An accordion has a vertical layout with header buttons that span the width of the component. One header is associated with each child, and each header belongs to the accordion—not to the child. When a user clicks a header, the associated child is displayed below that header. The transition to the new child uses a transition animation. An accordion with children accepts focus, and changes the appearance of its headers to display focus. When a user tabs into an accordion, the selected header displays the focus indicator. An accordion with no children does not accept focus. Clicking components that can take focus within the selected child gives them focus. When an Accordion instance has focus, you can use the following keys to control it: Key
Description
Down Arrow, Right Arrow
Moves focus to the next child header. Focus cycles from last to first without changing the selected child.
Up Arrow, Left Arrow
Moves focus to the previous child header. Focus cycles from first to last without changing the selected child.
End
Selects the last child.
Enter/Space
Selects the child associated with the header that has focus.
Home
Selects the first child.
Page Down
Selects the next child. Selection cycles from the last child to the first child.
Page Up
Selects the previous child. Selection cycles from the first child to the last child.
Shift+Tab
Moves focus to the previous component. This component may be inside the selected child, or outside the accordion; it is never another header in the same accordion.
Tab
Moves focus to the next component. This component may be inside the selected child, or outside the accordion; it is never another header in the same accordion.
The Accordion component cannot be made accessible to screen readers.
96
Chapter 6: Components Dictionary
Using the Accordion component (Flash Professional only) You can use the Accordion component to present multipart forms. For example, a three-child accordion might present forms where the user fills out her shipping address, billing address, and payment information for an e-commerce transaction. Using an accordion instead of multiple web pages minimizes server traffic and allows the user to maintain a better sense of progress and context in an application. Accordion parameters You can set the following authoring parameters for each Accordion component instance in the Property inspector or in the Component inspector: childSymbols is an array that specifies the linkage identifiers of the library symbols to be used to create the accordion’s children. The default value is [] (an empty array). childNames is an array that specifies the instance names of the accordion’s children. The values you enter will be the instance names for the child symbols you specify in the childSymbols parameter. The default value is [] (an empty array). childLabels is an array that specifies the text labels to use on the accordion’s headers. The default value is [] (an empty array). childIcons
is an array that specifies the linkage identifiers of the library symbols to be used as the icons on the accordion’s headers. The default value is [] (an empty array).
You can write ActionScript to control additional options for the Accordion component using its properties, methods, and events. For more information, see “Accordion class (Flash Professional only)” on page 105. Creating an application with the Accordion component In this example, an application developer is building the checkout section of an online store. The design calls for an accordion with three forms in which a user enters a shipping address, a billing address, and payment information. The shipping address and billing address forms are identical. To use screens to add an Accordion component to an application:
1. In Flash, select File > New and select Flash Form Application. 2. Double-click the text Form1, and enter the name addressForm.
Although it doesn’t appear in the library, the addressForm screen is a symbol of the Screen class. Because the Screen class is a subclass of the View class, an accordion can use it as a child. 3. With the form selected, in the Property inspector, set the form’s visible property to false.
This hides the contents of the form in the application; the form only appears in the accordion. 4. Drag components such as Label and TextInput from the Components panel onto the form to
create a mock address form; arrange them, and set their properties in the Parameters tab of the Component inspector. Position the form elements in the upper left corner of the form. This corner of the form is placed in the upper left corner of the accordion.
Accordion component (Flash Professional only)
97
5. Repeat steps 2-4 to create a screen named checkoutForm. 6. Create a new screen named accordionForm. 7. Drag an Accordion component from the Components panel to the accordionForm form, and
name it myAccordion. 8. With myAccordion selected, in the Property inspector, do the following: ■
For the childSymbols property, enter addressForm, addressForm, and checkoutForm. These strings specify the names of the screens used to create the accordion’s children. Note: The first two children are instances of the same screen, because the shipping address form and the billing address form are identical.
■
For the childNames property, enter shippingAddress, billingAddress, and checkout. These strings are the ActionScript names of the accordion’s children.
■
For the childLabels property, enter Shipping Address, Billing Address, and Checkout. These strings are the text labels on the accordion headers.
9. Select Control > Test Movie. To add an Accordion component to an application:
1. Select File > New and create a new Flash document. 2. Select Insert > New Symbol and name it AddressForm. 3. In the Create New Symbol dialog box, click the Advanced button and select Export for
ActionScript. In the AS 2.0 Class field, enter mx.core.View. To maintain tabbing order in an accordion’s children, the children must also be instances of the View class. 4. Drag components such as Label and TextInput from the Components panel onto the Stage to
create a mock address form; arrange them, and set their properties in the Parameters tab of the Component inspector. Position the form elements in relation to 0,0 (the middle) on the Stage. The 0,0 coordinate of the movie clip is placed in the upper left corner of the accordion. 5. Select Edit > Edit Document to return to the main Timeline. 6. Repeat steps 2-5 to create a movie clip named CheckoutForm. 7. Drag an Accordion component from the Components panel to add it to the Stage on the
main Timeline. 8. In the Property inspector, do the following: ■
Enter the instance name myAccordion.
■
For the childSymbols property, enter AddressForm, AddressForm, and CheckoutForm. These strings specify the names of the movie clips used to create the accordion’s children. Note: The first two children are instances of the same movie clip, because the shipping address form and the billing address form are identical.
98
Chapter 6: Components Dictionary
■
For the childNames property, enter shippingAddress, billingAddress, and checkout. These strings are the ActionScript names of the accordion’s children.
■
For the childLabels property, enter Shipping Address, Billing Address, and Checkout. These strings are the text labels on the accordion headers.
■
For the childIcons property, enter AddressIcon, AddressIcon, and CheckoutIcon. These strings specify the linkage identifiers of the movie clip symbols that are used as the icons on the accordion headers. You must create these movie clip symbols if you want icons in the headers.
9. Select Control > Test Movie. To use ActionScript to add children to an Accordion component:
1. Select File > New and create a Flash document. 2. Drag an Accordion component from the Components panel to the Stage. 3. In the Property inspector, enter the instance name myAccordion. 4. Drag a TextInput component to the Stage and delete it.
This adds the component to the library so that you can dynamically instantiate it in step 6. 5. In the Actions panel on Frame 1 of the Timeline, enter the following: myAccordion.createChild("View", "shippingAddress", {label: "Shipping Address"}); myAccordion.createChild("View", "billingAddress", {label: "Billing Address"}); myAccordion.createChild("View", "payment", {label: "Payment"});
This code calls the createChild() method to create its child views. 6. In the Actions panel on Frame 1, below the code you entered in step 5, enter the following code: var o = myAccordion.shippingAddress.createChild("TextInput", "firstName"); o.move(20, 38); o.setSize(116, 20); o = myAccordion.shippingAddress.createChild("TextInput", "lastName"); o.move(175, 38); o.setSize(145, 20);
This code adds component instances (two TextInput components) to the accordion’s children. Customizing the Accordion component (Flash Professional only) You can transform an Accordion component horizontally and vertically during authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()). The setSize() method and the Transform tool change only the width of the accordion’s headers and the width and height of its content area. The height of the headers and the width and height of the children are not affected. Calling the setSize() method is the only way to change the bounding rectangle of an accordion.
Accordion component (Flash Professional only)
99
If the headers are too small to contain their label text, the labels are clipped. If the content area of an accordion is smaller than a child, the child is clipped. Using styles with the Accordion component You can set style properties to change the appearance of the border and background of an Accordion component. If the name of a style property ends in “Color”, it is a color style property and behaves differently than noncolor style properties. For more information, see “Using styles to customize component color and text” on page 67. An Accordion component uses the following styles:
100
Style
Theme Description
themeColor
Halo
The base color scheme of a component. This is the only color style that doesn’t inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
backgroundColor
Both
The background color. The default color is white.
border styles
Both
The Accordion component uses a RectBorder instance as its border and responds to the styles defined on that class. See “RectBorder class” on page 647. The Accordion component’s default border style value is "solid".
headerHeight
Both
The height of the header buttons, in pixels. The default value is 22.
color
Both
The text color. The default value is 0x0B333C for the Halo theme and blank for the Sample theme.
disabledColor
Both
The color for text when the component is disabled. The default color is 0x848384 (dark gray).
embedFonts
Both
A Boolean value that indicates whether the font specified in fontFamily is an embedded font. This style must be set to true if fontFamily refers to an embedded font. Otherwise, the embedded font will not be used. If this style is set to true and fontFamily does not refer to an embedded font, no text will be displayed. The default value is false.
fontFamily
Both
The font name for the header labels. The default value is "_sans".
fontSize
Both
The point size for the font of the header labels. The default value is 10.
fontStyle
Both
The font style for the header labels; either "normal" or "italic". The default value is "normal".
fontWeight
Both
The font weight for the header labels; either "none" or "bold". The default value is "none". All components can also accept the value "normal" in place of "none" during a setStyle() call, but subsequent calls to getStyle() will return "none".
textDecoration
Both
The text decoration; either "none" or "underline".
Chapter 6: Components Dictionary
Style
Theme Description
openDuration
Both
The duration, in milliseconds, of the transition animation.
openEasing
Both
A reference to a tweening function that controls the animation. Defaults to sine in/out. For more information, see “Customizing component animations” on page 75.
Using skins with the Accordion component The Accordion component uses skins to represent the visual states of its header buttons. To skin the buttons and title bar while authoring, modify skin symbols in the Flash UI Components 2/ Themes/MMDefault/Accordion Assets skins states folder in the library of one of the themes FLA files. For more information, see “About skinning components” on page 80. An Accordion component is composed of its border, background, header buttons, and children. The border and background are provided by the RectBorder class by default. For information on skinning the RectBorder class, see “RectBorder class” on page 647. You can sking the headers with the skins listed below. Property
Description
Default value
falseUpSkin
The up (normal) state of the header above all collapsed children.
accordionHeaderSkin
falseDownSkin
The pressed state of the header above all collapsed children.
accordionHeaderSkin
falseOverSkin
The rolled-over state of the header above all collapsed accordionHeaderSkin children.
falseDisabled
The disabled state of the header above all collapsed children.
accordionHeaderSkin
trueUpSkin
The up (normal) state of the header above the expanded child.
accordionHeaderSkin
trueDownSkin
The pressed state of the header above the expanded child.
accordionHeaderSkin
trueOverSkin
The rolled-over state of the header above the expanded child.
accordionHeaderSkin
trueDisabledSkin
The disabled state of the header above the expanded child.
accordionHeaderSkin
Using ActionScript to draw the Accordion header
The default headers in both the Halo and Sample themes use the same skin element for all states and draw the actual graphics through ActionScript. The Halo implementation uses an extension of the RectBorder class and custom drawing API code to draw the states. The Sample implementation uses the same skin and the same ActionScript class as the Button skin.
Accordion component (Flash Professional only)
101
To create an ActionScript class to use as the skin and provide different states, the skin can read the borderStyle style property of the skin to determine the state. The following table shows the border style that is set for each skin: Property
Border style
falseUpSkin
falseup
falseDownSkin
falsedown
falseOverSkin
falserollover
falseDisabled
falsedisabled
trueUpSkin
trueup
trueDownSkin
truedown
trueOverSkin
truerollover
trueDisabledSkin
truedisabled
To create an ActionScript customized Accordion header skin:
1. Create a new ActionScript class file.
For this example, name the file RedGreenBlueHeader.as. 2. Copy the following ActionScript to the file: import mx.skins.RectBorder; import mx.core.ext.UIObjectExtensions; class RedGreenBlueHeader extends RectBorder { static var symbolName:String = "RedGreenBlueHeader"; static var symbolOwner:Object = RedGreenBlueHeader; function size():Void { var c:Number; // color var borderStyle:String = getStyle("borderStyle"); switch (borderStyle) { case "falseup": case "falserollover": case "falsedisabled": c = 0x7777FF; break; case "falsedown": c = 0x77FF77; break; case "trueup": case "truedown": case "truerollover": case "truedisabled": c = 0xFF7777; break; }
102
Chapter 6: Components Dictionary
clear(); lineStyle(0, 0, 100); beginFill(c, 100); drawRect(0, 0, __width, __height); endFill(); } // required for skins static function classConstruct():Boolean { UIObjectExtensions.Extensions(); _global.skinRegistry["AccordionHeaderSkin"] = true; return true; } static var classConstructed:Boolean = classConstruct(); static var UIObjectExtensionsDependency = UIObjectExtensions; }
This class creates a square box based on the border style: a blue box for the false up, rollover, and disabled states; a green box for the normal pressed state; and a red box for the expanded child. 3. Save the file. 4. Create a new FLA file. 5. Save the FLA file in the same folder as the AS file. 6. Create a new symbol by selecting Insert > New Symbol. 7. Set the name to AccordionHeaderSkin. 8. If the advanced view is not displayed, click the Advanced button. 9. Select Export for ActionScript.
The identifier will be automatically filled out with AccordionHeaderSkin. 10. Set the AS 2.0 class to RedGreenBlueHeader. 11. Ensure that Export in First Frame is already selected, and click OK. 12. Drag an Accordion component to the Stage. 13. Set the Accordion properties so that they display several children.
For example, set the childLabels to an array of [One,Two,Three] and childNames to an array of [one,two,three]. 14. Select Control > Test Movie. Using movie clips to customize the Accordion header skin
The above example demonstrates how to use an ActionScript class to customize the Accordion header skin, which is the method used by the skins provided in both the Halo and Sample themes. However, because the example uses simple colored boxes, it is simpler in this case to use different movie clip symbols as header skins.
Accordion component (Flash Professional only)
103
To create movie clip symbols for Accordion header skins:
1. Create a new FLA file. 2. Create a new symbol by selecting Insert > New Symbol. 3. Set the name to RedAccordionHeaderSkin. 4. If the advanced view is not displayed, click the Advanced button. 5. Select Export for ActionScript.
The identifier will be automatically filled out with RedAccordionHeaderSkin. 6. Leave the AS 2.0 Class text box blank. 7. Ensure that Export in First Frame is already selected, and click OK. 8. Open the new symbol for editing. 9. Use the drawing tools to create a box with a red fill and black line. 10. Set the border style to hairline. 11. Set the box, including the border, so that it is positioned at (0,0) and has a width and height of
100. The ActionScript code will size the skin as needed. 12. Repeat steps 2-11 and create green and blue skins, named accordingly. 13. Click the Back button to return to the main Timeline. 14. Drag an Accordion component to the stage. 15. Set the Accordion properties so that they display several children.
For example, set childLabels to an array of [One,Two,Three] and childNames to an array of [one,two,three]. 16. Copy the following ActionScript code to the Actions panel with the Accordion instance
Accordion class (Flash Professional only) Inheritance
MovieClip > UIObject class > UIComponent class > View > Accordion
ActionScript Class Name
mx.containers.Accordion
An Accordion component contains children that are displayed one at a time. Each child has a corresponding header button that is created when the child is created. A child must be an instance of UIObject. A movie clip symbol automatically becomes an instance of the UIObject class when it becomes a child of an accordion. However, to maintain tabbing order in an accordion’s children, the children must also be instances of the View class. If you use a movie clip symbol as a child, set its AS 2.0 Class field to mx.core.View so that it inherits from the View class. Setting a property of the Accordion class with ActionScript overrides the parameter of the same name set in the Property inspector or Component inspector. Each component class has a version property that is a class property. Class properties are available only on the class itself. The version property returns a string that indicates the version of the component. To access this property, use the following code: trace(mx.containers.Accordion.version); Note: The code trace(myAccordionInstance.version); returns undefined.
Method summary for the Accordion class The following table lists methods of the Accordion class. Method
Description
Accordion.createChild()
Creates a child for an Accordion instance.
Accordion.createSegment()
Creates a child for an Accordion instance. The parameters for this method are different from those of the createChild() method.
Accordion.destroyChildAt()
Destroys a child at a specified index position.
Accordion.getChildAt()
Gets a reference to a child at a specified index position.
Methods inherited from the UIObject class
The following table lists the methods the Accordion class inherits from the UIObject class. When calling these methods from the Accordion object, use the form accordionInstance.methodName. Method
Description
UIObject.createClassObject() Creates an object on the specified class. UIObject.createObject()
Creates a subobject on an object.
UIObject.destroyObject()
Destroys a component instance.
UIObject.doLater()
Calls a function when parameters have been set in the Property and Component inspectors.
Accordion component (Flash Professional only)
105
Method
Description
UIObject.getStyle()
Gets the style property from the style declaration or object.
UIObject.invalidate()
Marks the object so it will be redrawn on the next frame interval.
UIObject.move()
Moves the object to the requested position.
UIObject.redraw()
Forces validation of the object so it is drawn in the current frame.
UIObject.setSize()
Resizes the object to the requested size.
UIObject.setSkin()
Sets a skin in the object.
UIObject.setStyle()
Sets the style property on the style declaration or object.
Methods inherited from UIComponent class
The following table lists the methods the Accordion class inherits from the UIComponent class. When calling these methods from the Accordion object, use the form accordionInstance.methodName. Method
Description
UIComponent.getFocus()
Returns a reference to the object that has focus.
UIComponent.setFocus()
Sets focus to the component instance.
Property summary for the Accordion class The following table lists properties of the Accordion class. Property
Description
Accordion.numChildren
The number of children of an Accordion instance.
Accordion.selectedChild
A reference to the selected child.
Accordion.selectedIndex
The index position of the selected child.
Properties inherited from the UIObject class
The following table lists the properties the Accordion class inherits from the UIObject class. When accessing these properties, use the form accordionInstance.propertyName.
106
Property
Description
UIObject.bottom
The position of the bottom edge of the object, relative to the bottom edge of its parent. Read-only.
UIObject.height
The height of the object, in pixels. Read-only.
UIObject.left
The left edge of the object, in pixels. Read-only.
UIObject.right
The position of the right edge of the object, relative to the right edge of its parent. Read-only.
UIObject.scaleX
A number indicating the scaling factor in the x direction of the object, relative to its parent.
Chapter 6: Components Dictionary
Property
Description
UIObject.scaleY
A number indicating the scaling factor in the y direction of the object, relative to its parent.
UIObject.top
The position of the top edge of the object, relative to its parent. Read-only.
UIObject.visible
A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width
The width of the object, in pixels. Read-only.
UIObject.x
The left edge of the object, in pixels. Read-only.
UIObject.y
The top edge of the object, in pixels. Read-only.
Properties inherited from the UIComponent class
The following table lists the properties the Accordion class inherits from the UIComponent class. When accessing these properties, use the form accordionInstance.propertyName. Property
Description
UIComponent.enabled
Indicates whether the component can receive focus and input.
UIComponent.tabIndex
A number indicating the tab order for a component in a document.
Event summary for the Accordion class The following table lists an event of the Accordion class. Event
Description
Accordion.change
Broadcast to all registered listeners when the selectedIndex and selectedChild properties of an accordion change because of a user’s mouse click or keypress.
Events inherited from the UIObject class
The following table lists the events the Accordion class inherits from the UIObject class. Event
Description
UIObject.draw
Broadcast when an object is about to draw its graphics.
UIObject.hide
Broadcast when an object’s state changes from visible to invisible.
UIObject.load
Broadcast when subobjects are being created.
UIObject.move
Broadcast when the object has moved.
UIObject.resize
Broadcast when an object has been resized.
UIObject.reveal
Broadcast when an object’s state changes from invisible to visible.
UIObject.unload
Broadcast when the subobjects are being unloaded.
Accordion component (Flash Professional only)
107
Events inherited from the UIComponent class
The following table lists the events the Accordion class inherits from the UIComponent class. Event
Description
UIComponent.focusIn
Broadcast when an object receives focus.
UIComponent.focusOut
Broadcast when an object loses focus.
UIComponent.keyDown
Broadcast when a key is pressed.
UIComponent.keyUp
Broadcast when a key is released.
Accordion.change Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage listenerObject = new Object(); listenerObject.change = function(eventObject){ // insert your code here } myAccordionInstance.addEventListener("change", listenerObject) Description
Event; broadcast to all registered listeners when the selectedIndex and selectedChild properties of an accordion change. This event is broadcast only when a user’s mouse click or keypress changes the value of selectedChild or selectedIndex—not when the value is changed with ActionScript. This event is broadcast before the transition animation occurs. Version 2 components use a dispatcher/listener event model. The Accordion component dispatches a change event when one of its buttons is clicked and the event is handled by a function (also called a handler) on a listener object (listenerObject) that you create. You call the addEventListener() method and pass it a reference to the handler as a parameter. When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. For more information, see “EventDispatcher class” on page 415. The Accordion change event also contains two unique event object properties:
• •
108
newValue prevValue
Number; the index of the child that is about to be selected. Number; the index of the child that was previously selected.
Chapter 6: Components Dictionary
Example
In the following example, a handler called myAccordionListener is defined and passed to the myAccordion.addEventListener() method as the second parameter. The event object is captured by the change handler in the eventObject parameter. When the change event is broadcast, a trace statement is sent to the Output panel. myAccordionListener = new Object(); myAccordionListener.change = function(){ trace("Changed to different view"); } myAccordion.addEventListener("change", myAccordionListener);
Accordion.createChild() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myAccordion.createChild(classOrSymbolName, instanceName[, initialProperties]) Parameters
Either the constructor function for the class of the UIObject to be instantiated, or the linkage name (a reference to the symbol to be instantiated). The class must be UIObject or a subclass of UIObject, but most often it is View object or a subclass of View.
classOrSymbolName
instanceName
The instance name of the new instance.
An optional parameter that specifies initial properties for the new instance. You can use the following properties:
initialProperties
• •
label
A string that specifies the text label that the new child instance uses on its header.
A string that specifies the linkage identifier of the library symbol that the child uses for the icon on its header.
icon
Returns
A reference to an instance of the UIObject that is the newly created child. Description
Method (inherited from View); creates a child for the accordion. The newly created child is added to the end of the list of children owned by the accordion. Use this method to place views inside the accordion. The created child is an instance of the class or movie clip symbol specified in the classOrSymbolName parameter. You can use the label and icon properties to specify a text label and an icon for the associated accordion header for each child in the initialProperties parameter. When each child is created, it is assigned an index number in the order of creation and the numChildren property is increased by 1.
Accordion component (Flash Professional only)
109
Example
The following code creates an instance of the PaymentForm movie clip symbol named payment as the last child of myAccordion: var child = myAccordion.createChild("PaymentForm", "payment", {label: "Payment", Icon: "payIcon"}); child.cardType.text = "Visa"; child.cardNumber.text = "1234567887654321";
The following code creates a child that is an instance of the View class: var child = myAccordion.createChild(mx.core.View, "payment", {label: "Payment", Icon: "payIcon"}); child.cardType.text = "Visa"; child.cardNumber.text = "1234567887654321";
The following code also creates a child that is an instance of the View class, but it uses import to reference the constructor for the View class: import mx.core.View var child = myAccordion.createChild(View, "payment", {label: "Payment", Icon: "payIcon"}); child.cardType.text = "Visa"; child.cardNumber.text = "1234567887654321";
Accordion.createSegment() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myAccordion.createSegment(classOrSymbolName, instanceName[, label[, icon]]) Parameters classOrSymbolName Either a reference to the constructor function for the class of the UIObject to be instantiated, or the linkage name of the symbol to be instantiated. The class must be UIObject or a subclass of UIObject, but most often it is View or a subclass of View. instanceName
The instance name of the new instance.
A string that specifies the text label that the new child instance uses on its header. This parameter is optional.
label
icon A string reference to the linkage identifier of the library symbol that the child uses for the icon on its header. This parameter is optional. Returns
A reference to the newly created UIObject instance.
110
Chapter 6: Components Dictionary
Description
Method; creates a child for the accordion. The newly created child is added to the end of the list of children owned by the accordion. Use this method to place views inside the accordion. The created child is an instance of the class or movie clip symbol specified in the classOrSymbolName parameter. You can use the label and icon parameters to specify a text label and an icon for the associated accordion header for each child. The createSegment() method differs from the createChild() method in that label and icon are passed directly as parameters, not as properties of an initalProperties parameter. When each child is created, it is assigned an index number in the order of creation, and the numChildren property is increased by 1. Example
The following example creates an instance of the PaymentForm movie clip symbol named payment as the last child of myAccordion: var child = myAccordion.createSegment("PaymentForm", "payment", "Payment", "payIcon"); child.cardType.text = "Visa"; child.cardNumber.text = "1234567887654321";
The following code creates a child that is an instance of the View class: var child = myAccordion.createSegment(mx.core.View, "payment", {label: "Payment", Icon: "payIcon"}); child.cardType.text = "Visa"; child.cardNumber.text = "1234567887654321";
The following code also creates a child that is an instance of the View class, but it uses import to reference the constructor for the View class: import mx.core.View var child = myAccordion.createSegment(View, "payment", {label: "Payment", Icon: "payIcon"}); child.cardType.text = "Visa"; child.cardNumber.text = "1234567887654321";
Accordion.destroyChildAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myAccordion.destroyChildAt(index) Parameters index The index number of the accordion child to destroy. Each child of an accordion is assigned a zero-based index number in the order in which it was created.
Accordion component (Flash Professional only)
111
Returns
Nothing. Description
Method (inherited from View); destroys one of the accordion’s children. The child to be destroyed is specified by its index, which is passed to the method in the index parameter. Calling this method destroys the corresponding header as well. If the destroyed child is selected, a new selected child is chosen. If there is a next child, it is selected. If there is no next child, the previous child is selected. If there is no previous child, the selection is undefined. Note: Calling destroyChildAt() decreases the numChildren property by 1. Example
The following code destroys the last child of myAccordion: myAccordion.destroyChildAt(myAccordion.numChildren - 1); See also Accordion.createChild()
Accordion.getChildAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myAccordion.getChildAt(index) Parameters
The index number of an accordion child. Each child of an accordion is assigned a zero-based index in the order in which it was created.
index
Returns
A reference to the instance of the UIObject at the specified index. Description
Method; returns a reference to the child at the specified index. Each accordion child is given an index number for its position. This index number is zero-based, so the first child is 0, the second child is 1, and so on. Example
The following code gets a reference to the last child of myAccordion: var lastChild:UIObject = myAccordion.getChildAt(myAccordion.numChildren - 1);
112
Chapter 6: Components Dictionary
Accordion.numChildren Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myAccordion.numChildren Description
Property (inherited from View); indicates the number of children (of type UIObject) in an Accordion instance. Headers are not counted as children. Each accordion child is given an index number for its position. This index number is zero-based, so the first child is 0, the second child is 1, and so on. The code myAccordion.numChild - 1 always refers to the last child added to an accordion. For example, if there were seven children in an accordion, the last child would have the index 6. The numChildren property is not zero-based, so the value of myAccordion.numChildren would be 7. The result of 7 - 1 is 6, which is the index number of the last child. Example
The following example selects the last child: myAccordion.selectedIndex = myAccordion.numChildren - 1;
Accordion.selectedChild Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myAccordion.selectedChild Description
Property; the selected child (of type UIObject) if one or more children exist; undefined if no children exist. If the accordion has children, the code myAccordion.selectedChild is equivalent to the code myAccordion.getChildAt(myAccordion.selectedIndex). Setting this property to a child causes the accordion to begin the transition animation to display the specified child. Changing the value of selectedChild also changes the value of selectedIndex.
Accordion component (Flash Professional only)
113
The default value is myAccordion.getChildAt(0) if the accordion has children. If the accordion doesn’t have children, the default value is undefined. Example
The following example retrieves the label of the selected child view: var selectedLabel = myAccordion.selectedChild.label;
The following example sets the payment form to be the selected child view: myAccordion.selectedChild = myAccordion.payment; See also Accordion.selectedIndex
Accordion.selectedIndex Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myAccordion.selectedIndex Description
Property; the zero-based index of the selected child in an accordion with one or more children. For an accordion with no child views, the only valid value is undefined. Each accordion child is given an index number for its position. This index number is zero-based, so the first child is 0, the second child is 1, and so on. The valid values of selectedIndex are 0, 1, 2, ... , n - 1, where n is the number of children. Setting this property to a child causes the accordion to begin the transition animation to display the specified child. Changing the value of selectedIndex also changes the value of selectedChild. Example
The following example remembers the index of the selected child: var oldSelectedIndex = myAccordion.selectedIndex;
The following example selects the last child: myAccordion.selectedIndex = myAccordion.numChildren - 1; See also Accordion.numChildren, Accordion.selectedChild
114
Chapter 6: Components Dictionary
Alert component (Flash Professional only)
CHAPTER 6 Components Dictionary
The Alert component lets you display a window that presents the user with a message and response buttons. The window has a title bar that you can fill with text, a message that you can customize, and buttons whose labels you can change. An Alert window can have any combination of Yes, No, OK, and Cancel buttons, and you can change the button labels by using the Alert.yesLabel, Alert.click, Alert.okLabel, and Alert.cancelLabel properties. You cannot change the order of the buttons in an Alert window; the button order is always OK, Yes, No, Cancel. An Alert window closes when a user clicks any of its buttons. To display an Alert window, call the Alert.show() method. In order to call the method successfully, the Alert component must be in the library. By dragging the Alert component from the Components panel to the Stage and then deleting the component, you add the component to the library without making it visible in the document. The live preview for the Alert component is an empty window. When you add an Alert component to an application, you can use the Accessibility panel to make the component’s text and buttons accessible to screen readers. First, add the following line of code to enable accessibility: mx.accessibility.AlertAccImpl.enableAccessibility(); Note: You enable accessibility for a component only once, regardless of how many instances you have of the component.
Using the Alert component (Flash Professional only) You can use an Alert component whenever you want to announce something to a user. For example, you could display an alert when a user doesn’t fill out a form properly, when a stock hits a certain price, or when a user quits an application without saving the session. Alert parameters The Alert component has no authoring parameters. You must call the ActionScript Alert.show() method to display an Alert window. You can use other ActionScript properties to modify the Alert window in an application. For more information, see “Alert class (Flash Professional only)” on page 119. Creating an application with the Alert component The following procedure explains how to add an Alert component to an application while authoring. In this example, the Alert component appears when a stock hits a certain price. To create an application with the Alert component:
1. Double-click the Alert component in the Components panel to add it to the Stage. 2. Press Backspace (Windows) or Delete (Macintosh) to delete the component from the Stage.
This adds the component to the library, but doesn’t make it visible in the application.
Alert component (Flash Professional only)
115
3. In the Actions panel, enter the following code on Frame 1 of the Timeline to define an event
handler for the click event: import mx.controls.Alert; myClickHandler = function (evt){ if (evt.detail == Alert.OK){ trace("start stock app"); // startStockApplication(); } } Alert.show("Launch Stock Application?", "Stock Price Alert", Alert.OK | Alert.CANCEL, this, myClickHandler, "stockIcon", Alert.OK);
This code creates an Alert window with OK and Cancel buttons. When the user clicks either button, Flash calls the myClickHandler function. But when the user clicks the OK button, Flash calls the startStockApplication() function. Note: The Alert.show() method includes an optional parameter that displays an icon in the Alert window (in this example, an icon with the linkage identifier “stockIcon”). To include this icon in your test example, create a symbol named stockIcon and set it to Export for ActionScript in the Linkage Properties dialog box or the Create New Symbol dialog box.
4. Select Control > Test Movie.
Customizing the Alert component (Flash Professional only) The Alert component positions itself in the center of the component that was passed as its parent parameter. The parent must be a UIComponent object. If it is a movie clip, you can register the clip as mx.core.View so that it inherits from UIComponent. The Alert window automatically stretches horizontally to fit the message text or any buttons that are displayed. If you want to display large amounts of text, include line breaks in the text. The Alert component does not respond to the setSize() method. Using styles with the Alert component You can set style properties to change the appearance of an Alert component. If the name of a style property ends in “Color”, it is a color style property and behaves differently than noncolor style properties. For more information, see “Using styles to customize component color and text” on page 67. An Alert component supports the following styles: Style
Theme Description
themeColor
Halo
The base color scheme of a component. Possible values are "haloGreen", "haloBlue", and "haloOrange". The default value is "haloGreen".
backgroundColor
116
Both
Chapter 6: Components Dictionary
The background color. The default color is white for the Halo theme and 0xEFEBEF (light gray) for the Sample theme.
Style
Theme Description
border styles
Both
The Alert component uses a RectBorder instance as its border and responds to the styles defined on that class. See “RectBorder class” on page 647. The Alert component has a component-specific borderStyle setting of “alert” with the Halo theme and “outset” with the Sample theme.
color
Both
The text color. The default value is 0x0B333C for the Halo theme and blank for the Sample theme.
disabledColor
Both
The color for text when the component is disabled. The default color is 0x848384 (dark gray).
embedFonts
Both
A Boolean value that indicates whether the font specified in fontFamily is an embedded font. This style must be set to true if fontFamily refers to an embedded font. Otherwise, the embedded font will not be used. If this style is set to true and fontFamily does not refer to an embedded font, no text will be displayed. The default value is false.
fontFamily
Both
The font name for text. The default value is "_sans".
fontSize
Both
The point size for the font. The default value is 10.
fontStyle
Both
The font style: either "normal" or "italic". The default value is "normal".
fontWeight
Both
The font weight: either "none" or "bold". The default value is "none". All components can also accept the value "normal" in place of "none" during a setStyle() call, but subsequent calls to getStyle() will return "none".
textAlign
Both
The text alignment: either "left", "right", or "center". The default value is "left".
textDecoration
Both
The text decoration: either "none" or "underline". The default value is "none".
textIndent
Both
A number indicating the text indent. The default value is 0.
The Alert component includes three different categories of text. Setting the text properties for the Alert component itself provides default values for all three categories, as shown here: import mx.controls.Alert; _global.styles.Alert.setStyle("color", 0x000099); Alert.show("This is a test alert", "Title");
To set the text styles for one category individually, the Alert component provides static properties that are references to a CSSStyleDeclaration instance. Static property
Text affected
buttonStyleDeclaration
Button
messageStyleDeclaration
Message
titleStyleDeclaration
Title
Alert component (Flash Professional only)
117
The following example demonstrates how to set the title of an Alert component to be italicized: import mx.controls.Alert; import mx.styles.CSSStyleDeclaration; var titleStyles = new CSSStyleDeclaration(); titleStyles.setStyle("fontWeight", "bold"); titleStyles.setStyle("fontStyle", "italic"); Alert.titleStyleDeclaration = titleStyles; Alert.show("Name is a required field", "Validation Error");
The default title style declarations set fontWeight to "bold". When you override the titleStyleDeclaration property, this default is also overridden, so you must explicitly set fontWeight to "bold" if that setting is desired. Note: Text styles set on an Alert component provide default text styles to its components through style inheritance. For more information, see “Setting inheriting styles on a container” on page 71.
Using skins with the Alert component The Alert component extends the Window component and uses its title background skin for the title background, a RectBorder class instance for its border, and Button skins for the visual states of its buttons. To skin the buttons and title bar while authoring, modify the Flash UI Components 2/Themes/MMDefault/Window Assets/Elements/TitleBackground and Flash UI Components 2/Themes/MMDefault/Button Assets/ButtonSkin symbols. For more information, see “About skinning components” on page 80. The border and background are provided by the RectBorder class by default. For information on skinning the RectBorder class, see “RectBorder class” on page 647. An Alert component uses the following skin properties to dynamically skin the buttons and title bar: Property
Description
Default value
buttonUp
The up state of the buttons.
ButtonSkin
buttonUpEmphasized
The up state of the default button.
ButtonSkin
buttonDown
The pressed state of the buttons.
ButtonSkin
buttonDownEmphasized
The pressed state of the default button.
ButtonSkin
buttonOver
The rolled-over state of the buttons.
ButtonSkin
buttonOverEmphasized
The rolled-over state of the default button.
ButtonSkin
titleBackground
The window title bar.
TitleBackground
To set the title of an Alert component to a custom movie clip symbol:
1. Create a new FLA file. 2. Create a new symbol by selecting Insert > New Symbol. 3. Set the name to TitleBackground.
118
Chapter 6: Components Dictionary
4. If the advanced view is not displayed, click the Advanced button. 5. Select Export for ActionScript. 6. The identifier will be automatically filled out with TitleBackground. 7. Set the AS 2.0 class to mx.skins.SkinElement.
SkinElement is a simple class that can be used for all skin elements that don’t provide their own ActionScript impelmentation. It provides movement and sizing functionality required by the version 2 component framework. 8. Ensure that Export in First Frame is already selected. 9. Click OK. 10. Open the new symbol for editing. 11. Use the drawing tools to create a box with a red fill and black line. 12. Set the border style to hairline. 13. Set the box, including the border, so that is positioned at (0,0) and has a width of 100 and
height of 22. The Alert component will set the proper width of the skin as needed, but it will use the existing height as the height of the title. 14. Click the Back button to return to the main Timeline. 15. Drag an Alert component to the Stage and delete it.
This will add the Alert component to the library and available at run-time. 16. Add ActionScript code to the main Timeline to create a sample Alert instance. import mx.controls.Alert; Alert.show("This is a skinned Alert component","Title");
17. Select Control > Test Movie.
Alert class (Flash Professional only) Inheritance MovieClip > UIObject class > UIComponent class > View > ScrollView > Window component > Alert ActionScript Class Name
mx.controls.Alert
To use the Alert component, you drag an Alert component to the Stage and delete it so that the component is in the document library but not visible in the application. Then you call Alert.show() to display an Alert window. You can pass parameters to Alert.show() that add a message, a title bar, and buttons to the Alert window. Because ActionScript is asynchronous, the Alert component is not blocking, which means that the lines of ActionScript code that follow the call to Alert.show() run immediately. You must add listeners to handle the click events that are broadcast when a user clicks a button and then continue your code after the event is broadcast. Note: In operating environments that are blocking (for example, Microsoft Windows), a call to Alert.show() does not return until the user has taken an action, such as clicking a button.
Alert component (Flash Professional only)
119
To understand more about the Alert class, see “Window component” on page 878 and “PopUpManager class” on page 601. Method summary for the Alert class The following table lists the method of the Alert class. Method
Description
Alert.show()
Creates an Alert window with optional parameters.
Methods inherited from the UIObject class
The following table lists the methods the Alert class inherits from the UIObject class. Method
Description
UIObject.createClassObject() Creates an object on the specified class. UIObject.createObject()
Creates a subobject on an object.
UIObject.destroyObject()
Destroys a component instance.
UIObject.doLater()
Calls a function when parameters have been set in the Property and Component inspectors.
UIObject.getStyle()
Gets the style property from the style declaration or object.
UIObject.invalidate()
Marks the object so it will be redrawn on the next frame interval.
UIObject.move()
Moves the object to the requested position.
UIObject.redraw()
Forces validation of the object so it is drawn in the current frame.
UIObject.setSize()
Resizes the object to the requested size.
UIObject.setSkin()
Sets a skin in the object.
UIObject.setStyle()
Sets the style property on the style declaration or object.
Methods inherited from the UIComponent class
The following table lists the methods the Alert class inherits from the UIComponent class. Method
Description
UIComponent.getFocus()
Returns a reference to the object that has focus.
UIComponent.setFocus()
Sets focus to the component instance.
Methods inherited from the Window class
The following table lists the methods the Alert class inherits from the Window class.
120
Method
Description
Window.deletePopUp()
Removes a window instance created by PopUpManager.createPopUp().
Chapter 6: Components Dictionary
Property summary for the Alert class The following table lists properties of the Alert class. Property
Description
Alert.buttonHeight
The height of each button, in pixels. The default value is 22.
Alert.buttonWidth
The width of each button, in pixels. The default value is 100.
Alert.CANCEL
A constant hexadecimal value indicating whether a Cancel button should be displayed in the Alert window.
Alert.cancelLabel
The label text for the Cancel button.
Alert.click
The label text for the No button.
Alert.NO
A constant hexadecimal value indicating whether a No button should be displayed in the Alert window.
Alert.OK
A constant hexadecimal value indicating whether an OK button should be displayed in the Alert window.
Alert.okLabel
The label text for the OK button.
Alert.YES
A constant hexadecimal value indicating whether a Yes button should be displayed in the Alert window.
Alert.yesLabel
The label text for the Yes button.
Properties inherited from the UIObject class
The following table lists the properties the Alert class inherits from the UIObject class. When calling these properties from the Alert object, use the form Alert.propertyName. Property
Description
UIObject.bottom
The position of the bottom edge of the object, relative to the bottom edge of its parent. Read-only.
UIObject.height
The height of the object, in pixels. Read-only.
UIObject.left
The left edge of the object, in pixels. Read-only.
UIObject.right
The position of the right edge of the object, relative to the right edge of its parent. Read-only.
UIObject.scaleX
A number indicating the scaling factor in the x direction of the object, relative to its parent.
UIObject.scaleY
A number indicating the scaling factor in the y direction of the object, relative to its parent.
UIObject.top
The position of the top edge of the object, relative to its parent. Read-only.
UIObject.visible
A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width
The width of the object, in pixels. Read-only.
Alert component (Flash Professional only)
121
Property
Description
UIObject.x
The left edge of the object, in pixels. Read-only.
UIObject.y
The top edge of the object, in pixels. Read-only.
Properties inherited from the UIComponent class
The following table lists the properties the Alert class inherits from the UIComponent class. When calling these properties from the Alert object, use the form Alert.propertyName. Property
Description
UIComponent.enabled
Indicates whether the component can receive focus and input.
UIComponent.tabIndex
A number indicating the tab order for a component in a document.
Properties inherited from the Window class
The following table lists the properties the Alert class inherits from the Window class. Property
Description
Window.closeButton
Indicates whether a close button is (true) or is not (false) included on the title bar.
Window.content
A reference to the content (root movie clip) of the window.
Window.contentPath
Sets the name of the content to display in the window.
Window.title
The text that appears in the title bar.
Window.titleStyleDeclaration The style declaration that formats the text in the title bar.
Event summary for the Alert class The following table lists an event of the Alert class. Event
Description
Alert.click
Broadcast when a button in an Alert window is clicked.
Events inherited from the UIObject class
The following table lists the events the Alert class inherits from the UIObject class. When calling these events from the Alert object, use the form Alert.eventName.
122
Event
Description
UIObject.draw
Broadcast when an object is about to draw its graphics.
UIObject.hide
Broadcast when an object’s state changes from visible to invisible.
UIObject.load
Broadcast when subobjects are being created.
UIObject.move
Broadcast when the object has moved.
UIObject.resize
Broadcast when an object has been resized.
Chapter 6: Components Dictionary
Event
Description
UIObject.reveal
Broadcast when an object’s state changes from invisible to visible.
UIObject.unload
Broadcast when the subobjects are being unloaded.
Events inherited from the UIComponent class
The following table lists the events the Alert class inherits from the UIComponent class. When calling these events from the Alert object, use the form Alert.eventName. Event
Description
UIComponent.focusIn
Broadcast when an object receives focus.
UIComponent.focusOut
Broadcast when an object loses focus.
UIComponent.keyDown
Broadcast when a key is pressed.
UIComponent.keyUp
Broadcast when a key is released.
Events inherited from the Window class
The following table lists the events the Alert class inherits from the Window class. Event
Description
Window.click
Broadcast when the close button is clicked (released).
Window.complete
Broadcast when a window is created.
Window.mouseDownOutside
Broadcast when the mouse is clicked (released) outside the modal window.
Alert.buttonHeight Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.buttonHeight Description
Property (class); a class (static) property that changes the height of the buttons. The default value is 22. See also Alert.buttonWidth
Alert component (Flash Professional only)
123
Alert.buttonWidth Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.buttonWidth Description
Property (class); a class (static) property that changes the width of the buttons. The default value is 100. See also Alert.buttonHeight
Alert.CANCEL Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.CANCEL Description
Property (constant); a property with the constant hexadecimal value 0x8. This property can be used for the flags or defaultButton parameter of the Alert.show() method. When used as a value for the flags parameter, this property indicates that a Cancel button should be displayed in the Alert window. When used as a value for the defaultButton parameter, the Cancel button has initial focus and is triggered when the user presses Enter (Windows) or Return (Macintosh). If the user tabs to another button, that button is triggered when the user presses Enter. Example
The following example uses Alert.CANCEL and Alert.OK as values for the flags parameter and displays an Alert component with an OK button and a Cancel button: import mx.controls.Alert; Alert.show("This is a generic Alert window", "Alert Test", Alert.OK | Alert.CANCEL, this);
124
Chapter 6: Components Dictionary
Alert.cancelLabel Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.cancelLabel Description
Property (class); a class (static) property that indicates the label text on the Cancel button. Example
The following example sets the Cancel button’s label to “cancellation”: Alert.cancelLabel = "cancellation";
Event; broadcast to the registered listener when the OK, Yes, No, or Cancel button is clicked. Version 2 components use a dispatcher/listener event model. The Alert component dispatches a click event when one of its buttons is clicked and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You call the Alert.show() method and pass it the name of the handler as a parameter. When a button in the Alert window is clicked, the listener is called. When the event occurs, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The Alert.click event’s event object has an additional detail property whose value is Alert.OK, Alert.CANCEL, Alert.YES, or Alert.NO, depending on which button was clicked. For more information, see “EventDispatcher class” on page 415.
Alert component (Flash Professional only)
125
Example
In the following example, a handler called myClickHandler is defined and passed to the Alert.show() method as the fifth parameter. The event object is captured by myClickHandler in the evt parameter. The detail property of the event object is then used in a trace statement to send the name of the button that was clicked (Alert.OK or Alert.CANCEL) to the Output panel. import mx.controls.Alert; myClickHandler = function(evt){ if(evt.detail == Alert.OK){ trace(Alert.okLabel); }else if (evt.detail == Alert.CANCEL){ trace(Alert.cancelLabel); } } Alert.show("This is a test of errors", "Error", Alert.OK | Alert.CANCEL, this, myClickHandler);
Alert.NO Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.NO Description
Property (constant); a property with the constant hexadecimal value 0x2. This property can be used for the flags or defaultButton parameter of the Alert.show() method. When used as a value for the flags parameter, this property indicates that a No button should be displayed in the Alert window. When used as a value for the defaultButton parameter, the Cancel button has initial focus and is triggered when the user presses Enter (Windows) or Return (Macintosh). If the user tabs to another button, that button is triggered when the user presses Enter. Example
The following example uses Alert.NO and Alert.YES as values for the flags parameter and displays an Alert component with a No button and a Yes button: import mx.controls.Alert; Alert.show("This is a generic Alert window", "Alert Test", Alert.NO | Alert.YES, this);
126
Chapter 6: Components Dictionary
Alert.noLabel Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.noLabel Description
Property (class); a class (static) property that indicates the label text on the No button. Example
The following example sets the No button’s label to “nyet”: Alert.noLabel = "nyet";
Alert.OK Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.OK Description
Property (constant); a property with the constant hexadecimal value 0x4. This property can be used for the flags or defaultButton parameter of the Alert.show() method. When used as a value for the flags parameter, this property indicates that an OK button should be displayed in the Alert window. When used as a value for the defaultButton parameter, the OK button has initial focus and is triggered when the user presses Enter (Windows) or Return (Macintosh). If the user tabs to another button, that button is triggered when the user presses Enter. Example
The following example uses Alert.OK and Alert.CANCEL as values for the flags parameter and displays an Alert component with an OK button and a Cancel button: import mx.controls.Alert; Alert.show("This is a generic Alert window", "Alert Test", Alert.OK | Alert.CANCEL, this);
Alert component (Flash Professional only)
127
Alert.okLabel Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.okLabel Description
Property (class); a class (static) property that indicates the label text on the OK button. Example
The following example sets the OK button’s label to “okay”: Alert.okLabel = "okay";
Alert.show() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.show(message[, title[, flags[, parent[, clickHandler[, icon[, defaultButton]]]]]]) Parameters message title
The message to display. The text in the Alert title bar. This parameter is optional; if you omit it, the title bar is
blank. An optional parameter that indicates the buttons to display in the Alert window. The default value is Alert.OK, which displays an OK button. When you use more than one value, separate the values with a | character. Use one or more of the following values: Alert.OK, Alert.CANCEL, Alert.YES, Alert.NO. flags
You can also use Alert.NONMODAL to indicate that the Alert window is nonmodal. A nonmodal window allows a user to interact with other windows in the application. parent The parent window for the Alert component. The Alert window centers itself in the parent window. Use the value null or undefined to specify the _root Timeline. The parent window must inherit from the UIComponent class. You can register the parent window with mx.core.View to cause it to inherit from UIComponent. This parameter is optional.
128
Chapter 6: Components Dictionary
clickHandler A handler for the click events broadcast when the buttons are clicked. In addition to the standard click event object properties, there is an additional detail property, which contains the flag value of the button that was clicked (Alert.OK, Alert.CANCEL, Alert.YES, Alert.NO). This handler can be a function or an object. For more information, see “Using listeners to handle events” on page 56.
A string that is the linkage identifier of a symbol in the library; this symbol is used as an icon displayed to the left of the alert text. This parameter is optional.
icon
Indicates which button has initial focus and is clicked when a user presses Enter (Windows) or Return (Macintosh). If a user tabs to another button, that button is triggered when the Enter key is pressed.
defaultButton
This parameter can be one of the following values: Alert.OK, Alert.CANCEL, Alert.YES, Alert.NO. Returns
The Alert instance that is created. Description
Method (class); a class (static) method that displays an Alert window with a message, an optional title, optional buttons, and an optional icon. The title of the alert appears at the top of the window and is left-aligned. The icon appears to the left of the message text. The buttons are centered below the message text and the icon. Example
The following code is a simple example of a modal Alert window with an OK button: mx.controls.Alert.show("Hello, world!");
The following code defines a click handler that sends a message to the Output panel about which button was clicked: import mx.controls.Alert; myClickHandler = function(evt){ trace ("button " + evt.detail + " was clicked"); } Alert.show("This is a test of errors", "Error", Alert.OK | Alert.CANCEL, this, myClickHandler);
The event object’s detail property returns a number to represent each button. The OK button is 4, the Cancel button is 8, the Yes button is 1, and the No button is 2. Note: You must have an Alert component in the library for this code to display an alert. To add the component to the library, drag it to the Stage and then delete it.
Alert component (Flash Professional only)
129
Alert.YES Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.YES Description
Property (constant); a property with the constant hexadecimal value 0x1. This property can be used for the flags or defaultButton parameter of the Alert.show() method. When used as a value for the flags parameter, this property indicates that a Yes button should be displayed in the Alert window. When used as a value for the defaultButton parameter, the Yes button has initial focus and is triggered when the user presses Enter (Windows) or Return (Macintosh). If the user tabs to another button, that button is triggered when the user presses Enter. Example
The following example uses Alert.NO and Alert.YES as values for the flags parameter and displays an Alert component with a No button and a Yes button: import mx.controls.Alert; Alert.show("This is a generic Alert window", "Alert Test", Alert.NO | Alert.YES, this);
Alert.yesLabel Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Alert.yesLabel Description
Property (class); a class (static) property that indicates the label text on the Yes button. Example
The following example sets the OK button’s label to “da”: Alert.yesLabel = "da";
130
Chapter 6: Components Dictionary
CHAPTER 6 Components Dictionary
Button component
The Button component is a resizable rectangular user interface button. You can add a custom icon to a button. You can also change the behavior of a button from push to toggle. A toggle button stays pressed when clicked and returns to its up state when clicked again. A button can be enabled or disabled in an application. In the disabled state, a button doesn’t receive mouse or keyboard input. An enabled button receives focus if you click it or tab to it. When a Button instance has focus, you can use the following keys to control it: Key
Description
Shift+Tab
Moves focus to the previous object.
Spacebar
Presses or releases the component and triggers the click event.
Tab
Moves focus to the next object.
For more information about controlling focus, see “Creating custom focus navigation” on page 50 or “FocusManager class” on page 419. A live preview of each Button instance reflects changes made to parameters in the Property inspector or Component inspector during authoring. However, in the live preview a custom icon is represented on the Stage by a gray square. When you add the Button component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code: mx.accessibility.ButtonAccImpl.enableAccessibility();
You enable accessibility for a component only once. regardless of how many instances you have of the component. Using the Button component A button is a fundamental part of any form or web application. You can use buttons wherever you want a user to initiate an event. For example, most forms have a Submit button. You could also add Previous and Next buttons to a presentation. To add an icon to a button, you need to select or create a movie clip or graphic symbol to use as the icon. The symbol should be registered at 0,0 for appropriate layout on the button. Select the icon symbol in the Library panel, open the Linkage dialog box from the Library options menu, and enter a linkage identifier. This is the value to enter for the icon parameter in the Property inspector or Component inspector. You can also enter this value for the Button.icon ActionScript property. Note: If an icon is larger than the button, it extends beyond the button’s borders.
To designate a button as the default push button in an application (the button that receives the click event when a user presses Enter), use FocusManager.defaultPushButton.
Button component
131
Button parameters You can set the following authoring parameters for each Button component instance in the Property inspector or in the Component inspector: label
sets the value of the text on the button; the default value is Button.
icon
adds a custom icon to the button. The value is the linkage identifier of a movie clip or graphic symbol in the library; there is no default value.
toggle
turns the button into a toggle switch. If true, the button remains in the down state when clicked and returns to the up state when clicked again. If false, the button behaves like a normal push button; the default value is false. selected if the toggle parameter is true, this parameter specifies whether the button is pressed (true) or released (false). The default value is false. labelPlacement orients the label text on the button in relation to the icon. This parameter can be one of four values: left, right, top, or bottom; the default value is right. For more information, see Button.labelPlacement.
You can write ActionScript to control these and additional options for the Button component using its properties, methods, and events. For more information, see “Button class” on page 139. Creating an application with the Button component The following procedure explains how to add a Button component to an application while authoring. In this example, the button is a Help button with a custom icon that opens a Help system when a user clicks it. To create an application with the Button component:
1. Drag a Button component from the Components panel to the Stage. 2. In the Property inspector, enter the instance name helpBtn. 3. In the Property inspector, do the following: ■
Enter Help for the label parameter.
■
Enter HelpIcon for the icon parameter. To use an icon, there must be a movie clip or graphic symbol in the library with a linkage identifier to use as the icon parameter. In this example, the linkage identifier is HelpIcon.
■
Set the toggle property to true.
4. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code: function click(evt){ clippyHelper.enabled = evt.target.selected; } helpBtn.addEventListener("click", this);
The last line of code adds a click event handler to the helpBtn instance. The handler enables and disables the clippyHelper instance, which could be a Help panel of some sort.
132
Chapter 6: Components Dictionary
Customizing the Button component You can transform a Button component horizontally and vertically while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()) or any applicable properties and methods of the Button class (see “Button class” on page 139). Resizing the button does not change the size of the icon or label. The bounding box of a Button instance is invisible and also designates the hit area for the instance. If you increase the size of the instance, you also increase the size of the hit area. If the bounding box is too small to fit the label, the label is clipped to fit. If an icon is larger than the button, the icon extends beyond the button’s borders. Using styles with the Button component You can set style properties to change the appearance of a button instance. If the name of a style property ends in “Color”, it is a color style property and behaves differently than noncolor style properties. For more information, see “Using styles to customize component color and text” on page 67. A Button component supports the following styles: Style
Theme Description
themeColor
Halo
The base color scheme of a component. Possible values are "haloGreen", "haloBlue", and "haloOrange". The default value is "haloGreen".
backgroundColor
Sample The background color. The default value is 0xEFEBEF (light gray). The Halo theme uses 0xF8F8F8 (very light gray) for the button background color when the button is up and themeColor when the button is pressed. You can only modify the up background color in the Halo theme by skinning the button. See “Using skins with the Button component” on page 134.
border styles
Sample The Button component uses a RectBorder instance as its border in the Sample theme and responds to the styles defined on that class. See “RectBorder class” on page 647. With the Halo theme, the Button component uses a custom rounded border whose colors cannot be modified except for themeColor.
color
Both
The text color. The default value is 0x0B333C for the Halo theme and blank for the Sample theme.
disabledColor
Both
The color for text when the component is disabled. The default color is 0x848384 (dark gray).
Button component
133
Style
Theme Description
embedFonts
Both
A Boolean value that indicates whether the font specified in fontFamily is an embedded font. This style must be set to true if fontFamily refers to an embedded font. Otherwise, the embedded font will not be used. If this style is set to true and fontFamily does not refer to an embedded font, no text will be displayed. The default value is false.
fontFamily
Both
The font name for text. The default value is "_sans".
fontSize
Both
The point size for the font. The default value is 10.
fontStyle
Both
The font style: either "normal" or "italic". The default value is "normal".
fontWeight
Both
The font weight: either "none" or "bold". The default value is "none". All components can also accept the value "normal" in place of "none" during a setStyle() call, but subsequent calls to getStyle() will return "none".
textDecoration
Both
The text decoration: either "none" or "underline". The default value is "none".
Using skins with the Button component The Button component includes 32 different skins that can be customized to correspond to the border and icon in 16 different states. To skin the Button component while authoring, create new movie clip symbols with the desired graphics and set the symbol linkage identifiers using ActionScript. (See “Using ActionScript to draw Button skins” on page 136.) The default implementation of the Button skins provided with both the Halo and Sample themes uses the ActionScript drawing API to draw the button states, and uses a single movie clip symbol associated with one ActionScript class to provide all skins for the Button component. The Button component has many skins because a button has so many states, and a border and icon for each state. The state of a Button instance is controlled by four properties and user interaction. The properties that affect skins include the following:
134
Property
Description
emphasized
Provides two different looks for Button instances and is typically used to highlight one button, such as the default button in a form.
enabled
Shows whether or not the button is allowing user interaction.
toggle
Toggle buttons provide a selected and unselected value and use different skins to demonstate the current value. For a Button instance whose toggle property is set to false, the false skins are used. When the toggle property is true, the skin depends on the selected property.
selected
When the toggle property is set to true, this property determines if the Button is selected (true or false). Different skins are used to identify the value and by default are the only way this value is depicted on screen.
Chapter 6: Components Dictionary
If a button is enabled, it displays its over state when the pointer moves over it. The button receives input focus and displays its down state when it’s pressed. The button returns to its over state when the mouse is released. If the pointer moves off the button while the mouse is pressed, the button returns to its original state and it retains input focus. If the toggle parameter is set to true, the state of the button does not change until the mouse is released over it. If a button is disabled, it displays its disabled state, regardless of user interaction. A Button component supports the following skin properties: Property
Description
falseUpSkin
The up (normal) state.
falseDownSkin
The pressed state.
falseOverSkin
The over state.
falseDisabledSkin
The disabled state.
trueUpSkin
The toggled state.
trueDownSkin
The pressed-toggled state.
trueOverSkin
The over-toggled state.
trueDisabledSkin
The disabled-toggled state.
falseUpSkinEmphasized
The up (normal) state of an emphasized button.
falseDownSkinEmphasized
The pressed state of an emphasized button.
falseOverSkinEmphasized
The over state of an emphasized button.
falseDisabledSkinEmphasized
The disabled state of an emphasized button.
trueUpSkinEmphasized
The toggled state of an emphasized button.
trueDownSkinEmphasized
The pressed-toggled state of an emphasized button.
trueOverSkinEmphasized
The over-toggled state of an emphasized button.
trueDisabledSkinEmphasized
The disabled-toggled state of an emphasized button.
falseUpIcon
The icon up state.
falseDownIcon
The icon pressed state.
falseOverIcon
The icon over state.
falseDisabledIcon
The icon disabled state.
trueUpIcon
The icon toggled state.
trueOverIcon
The icon over-toggled state.
trueDownIcon
The icon pressed-toggled state.
trueDisabledIcon
The icon disabled-toggled state.
falseUpIconEmphasized
The icon up state of an emphasized button.
falseDownIconEmphasized
The icon pressed state of an emphasized button.
falseOverIconEmphasized
The icon over state of an emphasized button.
Button component
135
Property
Description
falseDisabledIconEmphasized
The icon disabled state of an emphasized button.
trueUpIconEmphasized
The icon toggled state of an emphasized button.
trueOverIconEmphasized
The icon over-toggled state of an emphasized button.
trueDownIconEmphasized
The icon pressed-toggled state of an emphasized button.
trueDisabledIconEmphasized
The icon disabled-toggled state of an emphasized button.
The default value for all skin properties ending in “Skin” is ButtonSkin, and the default for all “Icon” properties is undefined. The properties with the “Skin” suffix provide a background and border, whereas those with the “Icon” suffix provide a small icon. In addition to the icon skins, the Button component also supports a standard icon property. The difference between the standard property and style property is that through the style property you can set icons for the individual states, whereas with the standard property only one icon can be set and it applies to all states. If a Button instance has both the icon property and icon style properties set, the instance may not behave as anticipated. To see an interactive movie demonstrating when each skin is used, see Using Components Help. Using ActionScript to draw Button skins
The default skins in both the Halo and Sample themes use the same skin element for all states and draw the actual graphics through ActionScript. The Halo implementation uses an extension of the RectBorder class and custom drawing API code to draw the states. The Sample implementation uses the same skin and the same ActionScript class as the Button skin. To create an ActionScript class to use as the skin and provide different states, the skin can read the borderStyle style property of the skin and emphasized property of the parent to determine the state. The following table shows the border style that is set for each skin:
136
Property
Border style
falseUpSkin
falseup
falseDownSkin
falsedown
falseOverSkin
falserollover
falseDisabled
falsedisabled
trueUpSkin
trueup
trueDownSkin
truedown
trueOverSkin
truerollover
trueDisabledSkin
truedisabled
Chapter 6: Components Dictionary
To create an ActionScript customized Button skin:
1. Create a new ActionScript class file.
For this example, name the file RedGreenBlueSkin.as. 2. Copy the following ActionScript to the file: import mx.skins.RectBorder; import mx.core.ext.UIObjectExtensions; class RedGreenBlueSkin extends RectBorder { static var symbolName:String = "RedGreenBlueSkin"; static var symbolOwner:Object = RedGreenBlueSkin; function size():Void { var c:Number; // color var borderStyle:String = getStyle("borderStyle"); switch (borderStyle) { case "falseup": case "falserollover": case "falsedisabled": c = 0x7777FF; break; case "falsedown": c = 0x77FF77; break; case "trueup": case "truedown": case "truerollover": case "truedisabled": c = 0xFF7777; break; } clear(); var thickness = _parent.emphasized ? 2 : 0; lineStyle(thickness, 0, 100); beginFill(c, 100); drawRect(0, 0, __width, __height); endFill(); } // required for skins static function classConstruct():Boolean { UIObjectExtensions.Extensions(); _global.skinRegistry["ButtonSkin"] = true; return true; } static var classConstructed:Boolean = classConstruct(); static var UIObjectExtensionsDependency = UIObjectExtensions; }
Button component
137
This class creates a square box based on the border style: a blue box for the false up, rollover, and disabled states; a green box for the normal pressed state; and a red box for the expanded child. It draws a hairline border in the normal case and a thick border if the button is emphasized. 3. Save the file. 4. Create a new FLA file. 5. Save the FLA file in the same folder as the AS file. 6. Create a new symbol by selecting Insert > New Symbol. 7. Set the name to ButtonSkin. 8. If the advanced view is not displayed, click the Advanced button. 9. Select Export for ActionScript.
The identifier will be automatically filled out with ButtonSkin. 10. Set the AS 2.0 class to RedGreenBlueSkin. 11. Ensure that Export in First Frame is already selected, and click OK. 12. Drag a Button component to the Stage. 13. Select Control > Test Movie. Using movie clips to customize Button skins
The above example demonstrates how to use an ActionScript class to customize the Button skin, which is the method used by the skins provided in both the Halo and Sample themes. However, because the example uses simple colored boxes, it is simpler in this case to use different movie clip symbols as the skins. To create movie clip symbols for Button skins:
1. Create a new FLA file. 2. Create a new symbol by selecting Insert > New Symbol. 3. Set the name to RedButtonSkin. 4. If the advanced view is not displayed, click the Advanced button. 5. Select Export for ActionScript.
The identifier will be automatically filled out with RedButtonSkin. 6. Set the AS 2.0 class to mx.skins.SkinElement. 7. Ensure that Export in First Frame is already selected, and click OK. 8. Open the new symbol for editing. 9. Use the drawing tools to create a box with a red fill and black line. 10. Set the border style to hairline. 11. Set the box, including the border, so that it is positioned at (0,0) and has a width and height of
100. The SkinElement class resizes the content as appropriate.
138
Chapter 6: Components Dictionary
12. Repeat steps 2-11 and create green and blue skins, named accordingly. 13. Click the Back button to return to the main Timeline. 14. Drag a Button component to the Stage. 15. Set the toggled property value to true to see all three skins. 16. Copy the following ActionScript code to the Actions panel with the Button instance selected. onClipEvent(initialize) { falseUpSkin = "BlueButtonSkin"; falseDownSkin = "GreenButtonSkin"; falseOverSkin = "BlueButtonSkin"; falseDisabledSkin = "BlueButtonSkin"; trueUpSkin = "RedButtonSkin"; trueDownSkin = "RedButtonSkin"; trueOverSkin = "RedButtonSkin"; trueDisabledSkin = "RedButtonSkin"; }
17. Select Control > Test Movie.
Button class Inheritance
MovieClip > UIObject class > UIComponent class > SimpleButton class > Button
ActionScript Class Name
mx.controls.Button
The properties of the Button class let you do the following at runtime: add an icon to a button, create a text label, and indicate whether the button acts as a push button or as a toggle switch. Setting a property of the Button class with ActionScript overrides the parameter of the same name set in the Property inspector or Component inspector. The Button component uses the Focus Manager to override the default Flash Player focus rectangle and draw a custom focus rectangle with rounded corners. For more information, see “Creating custom focus navigation” on page 50. Each component class has a version property, which is a class property. Class properties are available only on the class itself. The version property returns a string that indicates the version of the component. To access this property, use the following code: trace(mx.controls.Button.version); Note: The code trace(myButtonInstance.version); returns undefined.
The Button component class is different from the built-in ActionScript Button object.
Button component
139
Method summary for the Button class There are no methods exclusive to the Button class. Methods inherited from the UIObject class
The following table lists the methods the Button class inherits from the UIObject class. When calling these methods from the Button object, use the form buttonInstance.methodName. Method
Description
UIObject.createClassObject() Creates an object on the specified class. UIObject.createObject()
Creates a subobject on an object.
UIObject.destroyObject()
Destroys a component instance.
UIObject.doLater()
Calls a function when parameters have been set in the Property and Component inspectors.
UIObject.getStyle()
Gets the style property from the style declaration or object.
UIObject.invalidate()
Marks the object so it will be redrawn on the next frame interval.
UIObject.move()
Moves the object to the requested position.
UIObject.redraw()
Forces validation of the object so it is drawn in the current frame.
UIObject.setSize()
Resizes the object to the requested size.
UIObject.setSkin()
Sets a skin in the object.
UIObject.setStyle()
Sets the style property on the style declaration or object.
Methods inherited from the UIComponent class
The following table lists the methods the Button class inherits from the UIComponent class. When calling these methods from the Button object, use the form buttonInstance.methodName. Method
Description
UIComponent.getFocus()
Returns a reference to the object that has focus.
UIComponent.setFocus()
Sets focus to the component instance.
Property summary for the Button class The following table lists properties of the Button class.
140
Property
Description
Button.icon
Specifies an icon for a button instance.
Button.label
Specifies the text that appears in a button.
Button.labelPlacement
Specifies the orientation of the label text in relation to an icon.
Chapter 6: Components Dictionary
Properties inherited from the SimpleButton class
The following table lists the properties the Button class inherits from the SimpleButton class. When accessing these properties, use the form buttonInstance.propertyName. Property
Description
SimpleButton.emphasized
Indicates whether a button has the look of a default push button.
SimpleButton.emphasizedStyleDeclaration The style declaration when the emphasized property is set to true. SimpleButton.selected
A Boolean value indicating whether the button is selected (true) or not (false). The default value is false.
SimpleButton.toggle
A Boolean value indicating whether the button behaves as a toggle switch (true) or not (false). The default value is false.
Properties inherited from the UIObject class
The following table lists the properties the Button class inherits from the UIObject class. When accessing these properties from the Button object, use the form buttonInstance.propertyName. Property
Description
UIObject.bottom
The position of the bottom edge of the object, relative to the bottom edge of its parent. Read-only.
UIObject.height
The height of the object, in pixels. Read-only.
UIObject.left
The left edge of the object, in pixels. Read-only.
UIObject.right
The position of the right edge of the object, relative to the right edge of its parent. Read-only.
UIObject.scaleX
A number indicating the scaling factor in the x direction of the object, relative to its parent.
UIObject.scaleY
A number indicating the scaling factor in the y direction of the object, relative to its parent.
UIObject.top
The position of the top edge of the object, relative to its parent. Read-only.
UIObject.visible
A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width
The width of the object, in pixels. Read-only.
UIObject.x
The left edge of the object, in pixels. Read-only.
UIObject.y
The top edge of the object, in pixels. Read-only.
Button component
141
Properties inherited from the UIComponent class
The following table lists the properties the Button class inherits from the UIComponent class. When accessing these properties from the Button object, use the form buttonInstance.propertyName. Property
Description
UIComponent.enabled
Indicates whether the component can receive focus and input.
UIComponent.tabIndex
A number indicating the tab order for a component in a document.
Event summary for the Button class There are no events exclusive to the Button class. Events inherited from the SimpleButton class
The following table lists the events the Button class inherits from the SimpleButton class. Property
Description
SimpleButton.click
Broadcast when a button is clicked.
Events inherited from the UIObject class
The following table lists the events the Button class inherits from the UIObject class. Event
Description
UIObject.draw
Broadcast when an object is about to draw its graphics.
UIObject.hide
Broadcast when an object’s state changes from visible to invisible.
UIObject.load
Broadcast when subobjects are being created.
UIObject.move
Broadcast when the object has moved.
UIObject.resize
Broadcast when an object has been resized.
UIObject.reveal
Broadcast when an object’s state changes from invisible to visible.
UIObject.unload
Broadcast when the subobjects are being unloaded.
Events inherited from the UIComponent class
The following table lists the events the Button class inherits from the UIComponent class.
Property; a string that specifies the linkage identifier of a symbol in the library to be used as an icon for a button instance. The icon can be a movie clip symbol or a graphic symbol with an upper left registration point. You must resize the button if the icon is too large to fit; neither the button nor the icon resizes automatically. If an icon is larger than a button, the icon extends over the borders of the button. To create a custom icon, create a movie clip or graphic symbol. Select the symbol on the Stage in symbol-editing mode and enter 0 in both the X and Y boxes in the Property inspector. In the Library panel, select the movie clip and select Linkage from the Library options menu. Select Export for ActionScript, and enter an identifier in the Identifier text box. The default value is an empty string (""), which indicates that there is no icon. Use the labelPlacement property to set the position of the icon in relation to the button. Note: The icon does not appear on the Stage in Flash. You must choose Control > Test Movie to see the icon. Example
The following code assigns the movie clip from the Library panel with the linkage identifier happiness to the Button instance as an icon: myButton.icon = "happiness" See also Button.labelPlacement
Button.label Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage buttonInstance.label
Button component
143
Description
Property; specifies the text label for a button instance. By default, the label appears centered on the button. Calling this method overrides the label authoring parameter specified in the Property inspector or the Component inspector. The default value is "Button". Example
The following code sets the label to “Remove from list”: buttonInstance.label = "Remove from list"; See also Button.labelPlacement
Property; sets the position of the label in relation to the icon. The default value is "right". The following are the four possible values; the icon and label are always centered vertically and horizontally within the bounding area of the button:
• • • •
The label is set to the right of the icon.
"right"
The label is set to the left of the icon.
"left" "bottom" "top"
The label is set below the icon.
The label is set above the icon.
Example
The following code sets the label to the left of the icon. The second line of the code sends the value of the labelPlacement property to the Output panel: iconInstance.labelPlacement = "left"; trace(iconInstance.labelPlacement);
144
Chapter 6: Components Dictionary
CellRenderer API
CHAPTER 6 Components Dictionary
The CellRenderer API is a set of properties and methods that the list-based components (List, DataGrid, Tree, Menu, and ComboBox) use to manipulate and display custom cell content for each of their rows. This customized cell can contain a prebuilt component, such as a CheckBox component, or any class you create. Understanding the List class To use the CellRenderer API, you need an advanced understanding of the List class. The DataGrid, Tree, Menu, and ComboBox components are extensions of the List class, so understanding the List class lets you understand them as well. About the composition of the List component List components are composed of rows. These rows display rollover and selection highlights, are used as hit states for row selection, and play a vital part in scrolling. Aside from selection highlights and icons (such as the node icons and expander arrows of a Tree component), a row consists of one cell (or, in the case of the DataGrid component, many cells). In the default case, these cells are TextField objects that implement the CellRenderer API. However, you can tell a List component to use a different class of component as the cell for each row. The only requirement is that the class must implement the CellRenderer API, which the List component uses for communicating with the cell.
The stacking order of a row in a List or DataGrid component Note: If a cell has button event handlers (onPress and so on), the background hit area may not receive input necessary to trigger the events.
About the scrolling behavior of the List component The List class uses a fairly complex algorithm for scrolling. A list only lays out as many rows as it can display at once; items beyond the value of the rowCount property don’t get rows at all. When the list scrolls, it moves all the rows up or down (depending on the scrolling direction). The list then recycles the rows that are scrolled out of view; it reinitializes them and uses them for the new rows being scrolled into view. To do this, it sets the value of the old row to the new item in the view and moves the old row to where the new item is scrolled into view.
CellRenderer API
145
Because of this scrolling behavior, you cannot expect a cell to be used for only one value. Recycling of rows means that the cell renderer must know how to completely reset its state when it is set to a new value. For example, if your cell renderer creates an icon to display one item, it might need to remove that icon when another item is rendered with it. Assume your cell renderer is a container that will be filled with numerous item values over time, and it has to know how to completely change itself from displaying one value to displaying another. In fact, your cell should even know how to properly render undefined items, which might mean removing all old content in the cell. Using the CellRenderer API You must write a class with four methods (CellRenderer.getPreferredHeight(), CellRenderer.getPreferredWidth(), CellRenderer.setSize(), and CellRenderer.setValue()) that the list-based component uses to communicate with the cell. The class must be specified in the AS 2.0 Class text box in the Linkage Properties dialog box of a movie clip symbol in your Flash application. You can look at the CheckCellRenderer class that implements the Cell Renderer API for an example; it’s located in FirstRun/classes/mx/controls/ cells.
There are two methods and a property (CellRenderer.getCellIndex(), and CellRenderer.listOwner) that are given automatically to a cell to allow it to communicate with the list-based component. For example, suppose a cell contains a check box that, when selected, causes a row to be selected. The cell renderer needs a reference to the list-based component that contains it in order to call the component’s selectedIndex property. Also, the cell needs to know which item index it is currently rendering so that it can set selectedIndex to the correct number; the cell can use CellRenderer.listOwner and CellRenderer.getCellIndex() to do so. You do not need to implement these ActionScript elements; the cell receives them automatically when it is placed in the list-based component. CellRenderer.getDataLabel(),
146
Chapter 6: Components Dictionary
Simple cell renderer example This section presents an example of a cell renderer that displays multiple lines of text in a cell. A cell renderer class must implement the following methods:
To test this cell renderer, create a Flash document with a list-based component. You must also create an empty movie clip and link it to the ActionScript 2.0 class MultiLineCell. Then, set the cellRenderer property of the component to the linkage identifier of the movie clip. For example, if you use a DataGrid component with the instance name grid and a movie clip with the linkage identifier MultiLineCell, the following code would cause the first column of the grid to render with multiline text: grid.getColumnAt(0).cellRenderer = "MultiLineCell"; Note: Remember to add data to the DataGrid component.
If you were using a ComboBox component, you could write the following code: comboBox.dropdown.cellRenderer = "MultiLineCell"
The following is the code for the MultiLineCell.as file: class { var var var
MultiLineCell extends mx.core.UIComponent multiLineLabel; //the label to be used for text owner; // the row that contains this cell listOwner; // the List/grid/tree that contains this cell
// empty constructor function MultiLineCell() { } // UIObject expects you to fill in createChildren by instantiating // all the movie clip assets you might need upon initialization. // Here, it's just a label. function createChildren():Void { // createLabel is a useful method of UIObject--all components use this
CellRenderer API
147
var c = multiLineLabel = createLabel("multiLineLabel", 10); // links the style of the label to the // style of the grid c.styleName = listOwner; c.selectable = false; c.tabEnabled = false; c.background = false; c.border = false; c.multiline = true; c.wordWrap = true; } // // // //
By extending UIComponent, you get setSize for free; however, UIComponent expects you to implement size(). Assume __width and __height are set for you now. You're going to expand the cell to fit the whole rowHeight. function size():Void { // __width and __height are the underlying variables // of the getter/setters .width and .height var c = multiLineLabel; c._width = __width; c._height = __height; } function getPreferredHeight():Number { /* The cell is given a property, "owner", that references the row. It’s always preferred that the cell take up most of the row's height. */ return owner.__height - 4; } function setValue(suggested:String, item:Object, selected:Boolean):Void { // Set the text property of the label // You could also set the text property to a variable. multiLineLabel.text = "This text wraps to two lines!"; } // function getPreferredWidth :: only necessary for menu // function getCellIndex :: not used in this cell renderer // function getDataLabel :: not used in this cell renderer }
Methods to implement for the CellRenderer API You must write a class with the following methods so that the List, DataGrid, Tree, or Menu component can communicate with the cell. Method
Description
CellRenderer.getPreferredHeight() Returns the preferred height of a cell. CellRenderer.getPreferredWidth()
148
Chapter 6: Components Dictionary
The preferred width of a cell.
Method
Description
CellRenderer.setSize()
Sets the width and height of a cell.
CellRenderer.setValue()
Sets the content to be displayed in the cell.
Methods provided by the CellRenderer API The List, DataGrid, Tree, and Menu components give the following methods to the cell when it is created within the component. You do not need to implement these methods. Method
Description
CellRenderer.getCellIndex()
Returns an object with two fields, columnIndex and rowIndex, that indicate the position of the cell.
CellRenderer.getDataLabel()
Returns a string containing the name of the cell renderer’s data field.
Properties provided by the CellRenderer API The List, DataGrid, Tree, and Menu component give the following properties to the cell when it is created within the component. You do not need to implement these properties. Property
Description
CellRenderer.listOwner
A reference to the List component that contains the cell.
An object with two fields: columnIndex and itemIndex. Description
Method; returns an object with two fields, columnIndex and itemIndex, that locate the cell in the component. Each field is an integer that indicates a cell’s column position and item position. For any components other than the DataGrid component, the value of columnIndex is always 0.
CellRenderer API
149
This method is provided by the List class; you do not have to implement it. Declare it in your cell renderer class as follows, and use it in the functions in your cell renderer: var getCellIndex:Function; Example
This example edits a DataGrid component’s data provider from within a cell: var index = getCellIndex(); var colName = listOwner.getColumnAt(index.columnIndex).columnName; listOwner.dataProvider.editField(index.itemIndex, colName, someVal);
Method; returns a string containing the name of the cell renderer’s data field. For the DataGrid component, this method returns the column name for the current cell. This method is provided by the List class; you do not have to implement it. Declare it in your cell renderer class as follows, and use it in the functions in your cell renderer: var getDataLabel:Function; Example
The following code tells the cell that it’s rendering the data field "Price". The variable p is now equal to "Price": var p = getDataLabel();
Method; returns the preferred height of a cell. This is especially important for getting the right height of text within the cell. If you set this value higher than the rowHeight property of the component, cells will bleed above and below the rows. This method is not provided by the List class; you must implement it. It tells the rows of the list how to center the cell and how to adjust the cell’s height if necessary. If necessary, you can return a constant (for example, 22), or you can measure and return the height of the contents. You can also return owner.height, which is the height of the row. Example
This example returns the value 20, which indicates that the cell should be 20 pixels high: function getPreferredHeight(Void) :Number { return 20; }
This example returns a value that is 4 pixels less that the height of the row: function getPreferredHeight():Number { /* You know the cell is given a property, "owner", which is the row. It’s always preferred for the cell to take up most of the row's height. */ return owner.__height - 4; }
A value (of type Number) that indicates the correct width of the cell. Description
Method; the preferred width of a cell. If you specify a width greater than that of the component, the cell may be cut off. You need to implement this method only for the Menu component. Your cell will be sized to whatever the width of the row is, except in a menu, which must measure the text for the width of the row. Example
This example returns the value 3, which indicates that the cell should be three times bigger than the length of the string it is rendering: function getPreferredWidth():Number { return myString.length*3; }
This example comments out the getPreferredWidth() method: // function getPreferredWidth :: only really necessary for a menu
Property; a reference to the list that owns the cell. That list can be a DataGrid, Tree, List, or Menu component. This method is provided by the List class; you do not have to implement it. Declare it in your cell renderer class as follows, and use it as a reference back to the list (or tree, menu, or grid): var listOwner:MovieClip; // or UIObject, etc. Example
This example finds the list’s selected item in a cell: var s = listOwner.selectedItem;
Property; a reference to the row that contains the cell. This method is provided by the List class; you do not have to implement it. Declare it in your cell renderer class and use it as a reference: var owner:MovieClip; // or UIObject, etc.
A number that indicates the width at which to lay out the component.
height
A number that indicates the height at which to lay out the component.
Returns
Nothing. Description
Method; lets the list tell its cells the size at which they should lay themselves out. The cell renderer should do layout so that it fits in the specified area, or the cell may bleed into other parts of the list and appear broken. If the cell renderer extends the UIObject class, you should implement the size() method instead. Write the same function that you would write for setSize(), but use the width and height properties instead of parameters.
CellRenderer API
153
Example
This example sizes an image in the cell to fit within the bounds specified by the list: function setSize(w:Number, h:Number):Void { image._width = w-2; image._height = h-2; image._x = image._y = 1; }
This example is in a cell renderer class that extends UIComponent (which extends UIObject), so you must implement size() instead of setSize(), as follows: // // // //
By extending UIComponent, you get setSize for free; however, UIComponent expects you to implement size(). Assume __width and __height are set for you now. You’re going to expand the cell to fit the whole rowHeight.
function size():Void { // __width and __height are the underlying variables // of the getters/setters .width and .height. var c = multiLineLabel; c._width = __width; c._height = __height; }
A value to be used for the cell renderer’s text, if any is needed.
suggested
An object that is the entire item to be rendered. The cell renderer can use properties of this object for rendering.
item
selected
A string with the following possible values: "normal", "highlighted", and
"selected". Returns
Nothing.
154
Chapter 6: Components Dictionary
Description
Method; takes the values given and creates a representation of them in the cell. This resolves any difference between what was displayed in the cell and what needs to be displayed in the cell for the new item. (Remember that any cell could display many values during its time in the list.) This is the most important CellRenderer method, and you must implement it in every cell renderer. The setValue() method is called frequently (for example, when a rollover, a selection, column resizing, or scrolling occurs). Therefore, you should write if statements in the body of setValue() that allow code to run only if a change has occurred. See the “Example” section below. If a row is selected and the mouse pointer is over it, the value of the selected parameter is "highlighted", not "selected". This can cause problems if you’re trying to make the cell renderer behave differently according to whether the row is in a selected state. To test whether the current row is in a selected state, use the following code: var reallySelected:Boolean = selected ne "normal" && listOwner.selectedNode == item; Example
The following example shows how to use setValue() and editField() to reference a cell renderer instance in a grid. Because a particular cell might not exist on the Stage (for example, if it’s scrolled out of the display area) or because it might be reused to render another value, you cannot directly reference a specific cell renderer instance in the grid. Instead, use the data provider to communicate with a specific cell in the grid. The data provider holds all the state information about the grid. To display a given cell as enabled or selected (checked), there should be a corresponding field in the data provider to hold that information. The setValue() method of your cell renderer communicates changes in the data provider’s state to the cell. The following is a setValue() implementation from a theoretical cell renderer that renders a check box in the cells: function setValue(str, itm, sel) { /* Assume the data provider has two relevant fields for this cell : checked and enabled. The form of such a data provider might look like this: [ {field1:"DisplayMe", field2:"SomeString", checked:true, enabled:false} {field1:"DisplayMe", field2:"SomeString", checked:false, enabled:true} {field1:"DisplayMe", field2:"SomeString", checked:true, enabled:true} ] */ // redundancy checking if (myCheck.selected!=itm.checked){ myCheck.selected = itm.checked; }
CellRenderer API
155
if (myCheck.enabled!=itm.enabled){ myCheck.enabled = itm.enabled; } }
If you want to enable the check box on the second row, you communicate through the data provider. Any change to the data provider (when made through a DataProvider method such as DataProvider.editField()) calls setValue() to refresh the display of the grid. This code would be written in the Flash application, either on a frame, on an object, or in another class file (but not in the cell renderer class file): // calls setValue() again myGrid.editField(1, "enabled", true);
The following example loads an image in a loader component within the cell, depending on the value passed: function setValue(suggested, item, selected) : Void { // clear the loader loader.contentPath = undefined; // the list has URLs for different images in its data provider if (suggested!=undefined) loader.contentPath = suggested; }
The following example is from a multiline text cell renderer: function setValue(suggested:String, item:Object, selected:Boolean):Void { // adds the text to the label multiLineLabel.text = suggested; }
156
Chapter 6: Components Dictionary
CheckBox component
CHAPTER 6 Components Dictionary
A check box is a square box that can be selected or deselected. When it is selected, a check mark appears in the box. You can add a text label to a check box and place it to the left, right, top, or bottom. A check box can be enabled or disabled in an application. If a check box is enabled and a user clicks it or its label, the check box receives input focus and displays its pressed appearance. If a user moves the pointer outside the bounding area of a check box or its label while pressing the mouse button, the component’s appearance returns to its original state and it retains input focus. The state of a check box does not change until the mouse is released over the component. Additionally, the check box has two disabled states, selected and deselected, which do not allow mouse or keyboard interaction. If a check box is disabled, it displays its disabled appearance, regardless of user interaction. In the disabled state, a button doesn’t receive mouse or keyboard input. A CheckBox instance receives focus if a user clicks it or tabs to it. When a CheckBox instance has focus, you can use the following keys to control it: Key
Description
Shift+Tab
Moves focus to the previous element.
Spacebar
Selects or deselects the component and triggers the click event.
Tab
Moves focus to the next element.
For more information about controlling focus, see “Creating custom focus navigation” on page 50 or “FocusManager class” on page 419. A live preview of each CheckBox instance reflects changes made to parameters in the Property inspector or Component inspector during authoring. When you add the CheckBox component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility: mx.accessibility.CheckBoxAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances you have of the component. For more information, see Chapter 17, “Creating Accessible Content,” in Using Flash. Using the CheckBox component A check box is a fundamental part of any form or web application. You can use check boxes wherever you need to gather a set of true or false values that aren’t mutually exclusive. For example, a form collecting personal information about a customer could have a list of hobbies for the customer to select; each hobby would have a check box beside it.
CheckBox component
157
CheckBox parameters You can set the following authoring parameters for each CheckBox component instance in the Property inspector or in the Component inspector: label
sets the value of the text on the check box; the default value is defaultValue.
selected
sets the initial value of the check box to checked (true) or unchecked (false).
labelPlacement orients the label text on the check box. This parameter can be one of four values: left, right, top,
or bottom; the default value is right. For more information, see
CheckBox.labelPlacement.
You can write ActionScript to control these and additional options for the CheckBox component using its properties, methods, and events. For more information, see “CheckBox class” on page 161. Creating an application with the CheckBox component The following procedure explains how to add a CheckBox component to an application while authoring. The following example is a form for an online dating application. The form is a query that searches for possible dating matches for the customer. The query form must have a check box labeled Restrict Age that permits customers to restrict their search to a specified age group. When the Restrict Age check box is selected, the customer can then enter the minimum and maximum ages into two text fields. (These text fields are enabled only when the check box is selected.) To create an application with the CheckBox component:
1. Drag two TextInput components from the Components panel to the Stage. 2. In the Property inspector, enter the instance names minimumAge and maximumAge. 3. Drag a CheckBox component from the Components panel to the Stage. 4. In the Property inspector, do the following: ■
Enter restrictAge for the instance name.
■
Enter Restrict Age for the label parameter.
5. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code: restrictAgeListener = new Object(); restrictAgeListener.click = function (evt){ minimumAge.enabled = evt.target.selected; maximumAge.enabled = evt.target.selected; } restrictAge.addEventListener("click", restrictAgeListener);
This code creates a click event handler that enables and disables the minimumAge and maximumAge text field components, which have already been placed on Stage. For more information, see CheckBox.click and “TextInput component” on page 742.
158
Chapter 6: Components Dictionary
Customizing the CheckBox component You can transform a CheckBox component horizontally and vertically while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (UIObject.setSize()) or any applicable properties and methods of the CheckBox class. Resizing the check box does not change the size of the label or the check box icon; it only changes the size of the bounding box. The bounding box of a CheckBox instance is invisible and also designates the hit area for the instance. If you increase the size of the instance, you also increase the size of the hit area. If the bounding box is too small to fit the label, the label is clipped to fit. Using styles with the CheckBox component You can set style properties to change the appearance of a CheckBox instance. If the name of a style property ends in “Color”, it is a color style property and behaves differently than noncolor style properties. For more information, see “Using styles to customize component color and text” on page 67. A CheckBox component supports the following styles: Style
Theme Description
themeColor
Halo
The base color scheme of a component. Possible values are "haloGreen", "haloBlue", and "haloOrange". The default value is "haloGreen".
color
Both
The text color. The default value is 0x0B333C for the Halo theme and blank for the Sample theme.
disabledColor
Both
The color for text when the component is disabled. The default color is 0x848384 (dark gray).
embedFonts
Both
A Boolean value that indicates whether the font specified in fontFamily is an embedded font. This style must be set to true if fontFamily refers to an embedded font. Otherwise, the embedded font will not be used. If this style is set to true and fontFamily does not refer to an embedded font, no text will be displayed. The default value is false.
fontFamily
Both
The font name for text. The default value is "_sans".
fontSize
Both
The point size for the font. The default value is 10.
fontStyle
Both
The font style: either "normal" or "italic". The default value is "normal".
fontWeight
Both
The font weight: either "none" or "bold". The default value is "none". All components can also accept the value "normal" in place of "none" during a setStyle() call, but subsequent calls to getStyle() will return "none".
CheckBox component
159
Style
Theme Description
textDecoration
Both
symbolBackgroundColor
Sample The background color of the check box. The default value is 0xFFFFFF (white).
symbolBackgroundDisabledColor
Sample The background color of the check box when disabled. The default value is 0xEFEEEF (light gray).
symbolBackgroundPressedColor
Sample The background color of the check box when pressed. The default value is 0xFFFFFF (white).
symbolColor
Sample The color of the check mark. The default value is 0x000000 (black).
symbolDisabledColor
Sample The color of the disabled check mark. The default value is 0x848384 (dark gray).
The text decoration: either "none" or "underline". The default value is "none".
Using skins with the CheckBox component The CheckBox component uses symbols in the library to represent the button states. To skin the CheckBox component while authoring, modify symbols in the Library panel. The CheckBox component skins are located in the Flash UI Components 2/Themes/MMDefault/CheckBox Assets/states folder in the library of either the HaloTheme.fla file or the SampleTheme.fla file. For more information, see “About skinning components” on page 80. A CheckBox component uses the following skin properties: Property
Description
falseUpSkin
The up (normal) unchecked state. The default is CheckFalseUp.
falseDownSkin
The pressed unchecked state. The default is CheckFalseDown.
falseOverSkin
The over unchecked state. The default is CheckFalseOver.
falseDisabledSkin
The disabled unchecked state. The default is CheckFalseDisabled.
trueUpSkin
The toggled checked state. The default is CheckTrueUp.
trueDownSkin
The pressed checked state. The default is CheckTrueDown.
trueOverSkin
The over checked state. The default is CheckTrueOver.
trueDisabledSkin
The disabled checked state. The default is CheckTrueDisabled.
Each of these skins corresponds to the icon indicating the CheckBox state. The CheckBox component does not have a border or background. To create movie clip symbols for CheckBox skins:
1. Create a new FLA file. 2. Select File > Import > Open External Library, and select the HaloTheme.fla file.
This file is located in the application-level configuration folder. For the exact location on your operating system, see “About themes” on page 77.
160
Chapter 6: Components Dictionary
3. In the theme’s Library panel, expand the Flash UI Components 2/Themes/MMDefault folder
and drag the CheckBox Assets folder to the library for your document. 4. Expand the CheckBox Assets/States folder in the library of your document. 5. Open the symbols you want to customize for editing.
For example, open the CheckFalseDisabled symbol. 6. Customize the symbol as desired.
For example, change the inner white square to a light gray. 7. Repeat steps 5-6 for all symbols you want to customize.
For example, repeat the color change for the inner box of the CheckTrueDisabled symbol. 8. Click the Back button to return to the main Timeline. 9. Drag a CheckBox component to the Stage.
For this example, drag two instances to show the two new skin symbols. 10. Set the CheckBox instance properties as desired.
For this example, set one CheckBox instance to true, and use ActionScript to set both CheckBox instances to disabled. 11. Select Control > Test Movie.
CheckBox class Inheritance
MovieClip > UIObject class > UIComponent class > SimpleButton class > Button component > CheckBox
ActionScript Class Name
mx.controls.CheckBox
The properties of the CheckBox class let you create a text label and position it to the left, right, top, or bottom of a check box at runtime. Setting a property of the CheckBox class with ActionScript overrides the parameter of the same name set in the Property inspector or Component inspector. The CheckBox component uses the Focus Manager to override the default Flash Player focus rectangle and draw a custom focus rectangle with rounded corners. For more information, see “Creating custom focus navigation” on page 50. Each component class has a version property, which is a class property. Class properties are available only on the class itself. The version property returns a string that indicates the version of the component. To access this property, use the following code: trace(mx.controls.CheckBox.version); Note: The code trace(myCheckBoxInstance.version); returns undefined.
Method summary for the CheckBox class There are no methods exclusive to the CheckBox class.
CheckBox component
161
Methods inherited from the UIObject class
The following table lists the methods the CheckBox class inherits from the UIObject class. When calling these methods from the CheckBox object, use the form checkBoxInstance.methodName. Method
Description
UIObject.createClassObject() Creates an object on the specified class. UIObject.createObject()
Creates a subobject on an object.
UIObject.destroyObject()
Destroys a component instance.
UIObject.doLater()
Calls a function when parameters have been set in the Property and Component inspectors.
UIObject.getStyle()
Gets the style property from the style declaration or object.
UIObject.invalidate()
Marks the object so it will be redrawn on the next frame interval.
UIObject.move()
Moves the object to the requested position.
UIObject.redraw()
Forces validation of the object so it is drawn in the current frame.
UIObject.setSize()
Resizes the object to the requested size.
UIObject.setSkin()
Sets a skin in the object.
UIObject.setStyle()
Sets the style property on the style declaration or object.
Methods inherited from the UIComponent class
The following table lists the methods the CheckBox class inherits from the UIComponent class. When calling these methods from the CheckBox object, use the form checkBoxInstance.methodName. Method
Description
UIComponent.getFocus()
Returns a reference to the object that has focus.
UIComponent.setFocus()
Sets focus to the component instance.
Property summary for the CheckBox class The following table lists properties of the CheckBox class.
162
Property
Description
CheckBox.label
Specifies the text that appears next to a check box.
CheckBox.labelPlacement
Specifies the orientation of the label text in relation to a check box.
CheckBox.selected
Specifies whether the check box is selected (true) or deselected (false).
Chapter 6: Components Dictionary
Properties inherited from the UIObject class
The following table lists the properties the CheckBox class inherits from the UIObject class. When accessing these properties from the CheckBox object, use the form checkBoxInstance.propertyName. Property
Description
UIObject.bottom
The position of the bottom edge of the object, relative to the bottom edge of its parent. Read-only.
UIObject.height
The height of the object, in pixels. Read-only.
UIObject.left
The left edge of the object, in pixels. Read-only.
UIObject.right
The position of the right edge of the object, relative to the right edge of its parent. Read-only.
UIObject.scaleX
A number indicating the scaling factor in the x direction of the object, relative to its parent.
UIObject.scaleY
A number indicating the scaling factor in the y direction of the object, relative to its parent.
UIObject.top
The position of the top edge of the object, relative to its parent. Read-only.
UIObject.visible
A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width
The width of the object, in pixels. Read-only.
UIObject.x
The left edge of the object, in pixels. Read-only.
UIObject.y
The top edge of the object, in pixels. Read-only.
Properties inherited from the UIComponent class
The following table lists the properties the CheckBox class inherits from the UIComponent class. When accessing these properties from the CheckBox object, use the form checkBoxInstance.propertyName. Property
Description
UIComponent.enabled
Indicates whether the component can receive focus and input.
UIComponent.tabIndex
A number indicating the tab order for a component in a document.
CheckBox component
163
Properties inherited from the SimpleButton class
The following table lists the properties the CheckBox class inherits from the SimpleButton class. When accessing these properties from the CheckBox object, use the form checkBoxInstance.propertyName. Property
Description
SimpleButton.emphasized
Indicates whether a button has the appearance of a default push button.
SimpleButton.emphasizedStyleDeclaration The style declaration when the emphasized property is set to true. SimpleButton.selected
A Boolean value indicating whether the button is selected (true) or not (false). The default value is false.
SimpleButton.toggle
A Boolean value indicating whether the button behaves as a toggle switch (true) or not (false). The default value is false.
Properties inherited from the Button class
The following table lists the properties the CheckBox class inherits from the Button class. When accessing these properties from the CheckBox object, use the form checkBoxInstance.propertyName. Property
Description
Button.label
Specifies the text that appears in a button.
Button.labelPlacement
Specifies the orientation of the label text in relation to an icon.
Event summary for the CheckBox class The following table lists an event of the CheckBox class. Event
Description
CheckBox.click
Triggered when the mouse is clicked (released) over the check box, or if the check box has focus and the Spacebar is pressed.
Events inherited from the UIObject class
The following table lists the events the CheckBox class inherits from the UIObject class.
164
Event
Description
UIObject.draw
Broadcast when an object is about to draw its graphics.
UIObject.hide
Broadcast when an object’s state changes from visible to invisible.
UIObject.load
Broadcast when subobjects are being created.
UIObject.move
Broadcast when the object has moved.
UIObject.resize
Broadcast when an object has been resized.
Chapter 6: Components Dictionary
Event
Description
UIObject.reveal
Broadcast when an object’s state changes from invisible to visible.
UIObject.unload
Broadcast when the subobjects are being unloaded.
Events inherited from the UIComponent class
The following table lists the events the CheckBox class inherits from the UIComponent class. Event
Description
UIComponent.focusIn
Broadcast when an object receives focus.
UIComponent.focusOut
Broadcast when an object loses focus.
UIComponent.keyDown
Broadcast when a key is pressed.
UIComponent.keyUp
Broadcast when a key is released.
Events inherited from the SimpleButton class
The following table lists the event the CheckBox class inherits from the SimpleButton class. Event
Event; broadcast to all registered listeners when the mouse is clicked (released) over the check box, or if the check box has focus and the Spacebar is pressed.
CheckBox component
165
The first usage example uses an on() handler and must be attached directly to a CheckBox instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the check box myCheckBox, sends “_level0.myCheckBox” to the Output panel: on(click){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (checkBoxInstance) dispatches an event (in this case, click), and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. The event object has properties that contain information about the event. You can use these properties to write code that handles the event. Finally, you call the addEventListener() method (see EventDispatcher.addEventListener()) on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
This example, written on a frame of the Timeline, sends a message to the Output panel when a button called checkBoxInstance is clicked. The first line of code creates a listener object called form. The second line defines a function for the click event on the listener object. Inside the function is a trace() statement that uses the event object that is automatically passed to the function (in this example, eventObj) to generate a message. The target property of an event object is the component that generated the event (in this example, checkBoxInstance). The CheckBox.selected property is accessed from the event object’s target property. The last line calls addEventListener() from checkBoxInstance and passes it the click event and the form listener object as parameters. form = new Object(); form.click = function(eventObj){ trace("The selected property has changed to " + eventObj.target.selected); } checkBoxInstance.addEventListener("click", form);
The following code also sends a message to the Output panel when checkBoxInstance is clicked. The on() handler must be attached directly to checkBoxInstance: on(click){ trace("check box component was clicked"); } See also EventDispatcher.addEventListener()
Property; indicates the text label for the check box. By default, the label appears to the right of the check box. Setting this property overrides the label parameter specified in the Parameters tab of the Component Inspector panel. Example
The following code sets the text that appears beside the CheckBox component and sends the value to the Output panel: checkBox.label = "Remove from list"; trace(checkBox.label) See also CheckBox.labelPlacement
Property; a string that indicates the position of the label in relation to the check box. The following are the four possible values (the dotted lines represent the bounding area of the component; they are invisible in a document):
•
"right" The check box is pinned to the upper left corner of the bounding area. The label is set to the right of the check box. This is the default value.
CheckBox component
167
•
"left" The check box is pinned to the upper right corner of the bounding area. The label is set to the left of the check box.
•
"bottom"
•
"top"
The label is set below the check box. The check box and label are centered horizontally and vertically.
The label is placed below the check box. The check box and label are centered horizontally and vertically.
You can change the bounding area of a component while authoring by using the Transform command or at runtime using the UIObject.setSize() property. For more information, see “Customizing the CheckBox component” on page 159. Example
The following example sets the placement of the label to the left of the check box: checkBox_mc.labelPlacement = "left"; See also CheckBox.label
Property; a Boolean value that selects (true) or deselects (false) the check box. Example
The following example selects the instance checkbox1: checkbox1.selected = true;
168
Chapter 6: Components Dictionary
CHAPTER 6 Components Dictionary
Collection interface (Flash Professional only) ActionScript Class Name
mx.utils.Collection
The collection class is distributed in the common classes library as a compiled clip symbol. To access this class, select Window > Other Panels > Common Libraries > Classes > UtilsClasses. The collection interface lets you programmatically manage a group of related items, called collection items. Each collection item in this set has properties that are described in the metadata of the collection item class definition. Components can expose properties as collections, which you can manipulate while authoring by using the Values dialog box from the Component inspector. Using this dialog box, you can add items, remove items, change properties of items, and change the position of items within the collection. For more information on collections and collection items, see “About the Collection tag” on page 942. You typically use the collection interface with components that use the Collection metadata tag to create collection properties. Although you can create, access, and delete Collection instances programmatically, collections are most often used in the context of a component. Flash MX Professional 2004 provides implementations of both collection-related interfaces (CollectionImpl for Collection, and IteratorImpl for Iterator). Method summary for the Collection interface The following table lists the methods of the Collection interface. Method
Description
Collection.addItem()
Adds a new item to the end of the collection.
Collection.contains()
Indicates whether the collection contains the specified item.
Collection.clear()
Removes all elements from the collection.
Collection.getItemAt()
Returns an item within the collection by using its index.
Collection.getIterator()
Returns an iterator over the elements in the collection.
Collection.getLength()
Returns the number of items in the collection.
Collection.isEmpty()
Indicates whether the collection is empty.
Collection.removeItem()
Removes the specified item from the collection.
Collection.addItem() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage collection.addItem(item)
Collection interface (Flash Professional only)
169
Parameters item
The object to be added to the collection. If item is null, it is not added to the collection.
Returns
A Boolean value of true if the collection was changed as a result of the operation. Description
Method; adds a new item to the end of the collection. Example
The following example calls addItem(): on (click) { import CompactDisc; var myColl:mx.utils.Collection; myColl = _parent.thisShelf.MyCompactDiscs; myCD = new CompactDisc(); myCD.Artist = "John Coltrane"; myCD.Title = "Giant Steps"; var wasAdded:Boolean = myColl.addItem(myCD); }
Collection.contains() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage collection.contains(item) Parameters item
The object whose presence in the collection is to be tested.
Returns
A Boolean value of true if the collection contains item. Description
Method; indicates whether the collection contains the specified item. For Flash to consider the objects as equal, they must refer to the same object. If item is a different object, Collection.contains() returns false, even if the object’s properties are all equal.
170
Chapter 6: Components Dictionary
Example
The following example calls contains(): var myColl:mx.utils.Collection; myColl = _parent.thisShelf.MyCompactDiscs; var itr:mx.utils.Iterator = myColl.getIterator(); while (itr.hasNext()) { var cd:CompactDisc = CompactDisc(itr.next()); var title:String = cd.Title; var artist:String = cd.Artist; if(myColl.contains(cd)) { trace("myColl contains " + title); } else { trace("myColl does not contain " + title); } }
Collection.clear() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage collection.clear() Returns
Nothing. Description
Method; removes all of the elements from the collection. Example
The following example calls clear(): on (click) { var myColl:mx.utils.Collection; myColl = _parent.thisShelf.MyCompactDiscs; myColl.clear(); }
Collection interface (Flash Professional only)
171
Collection.getItemAt() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage collection.getItemAt(index) Parameters
A number that indicates the location of item within the collection. This is a zero-based index, so 0 retrieves the first item, 1 retrieves the second item, and so on.
index
Returns
An object containing a reference to the specified collection item, or null if index is out of bounds. Description
Method; returns an item within the collection by using its index. Example
The following example calls getItemAt(): //... var myColl:mx.utils.Collection; myColl = _parent.thisShelf.MyCompactDiscs; var myCD = CompactDisc(myColl.getItemAt(0)); if (myCD !=null) { trace("Retrieved " + myCD.Title); } //...
Collection.getIterator() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage collection.getIterator() Returns
An Iterator object that you can use to step through the collection.
172
Chapter 6: Components Dictionary
Description
Method; returns an iterator over the elements in the collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of a class that provides a guarantee). Example
The following example calls getIterator(): on (click) { var myColl:mx.utils.Collection; myColl = _parent.thisShelf.MyCompactDiscs; var itr:mx.utils.Iterator = myColl.getIterator(); while (itr.hasNext()) { var cd:CompactDisk = CompactDisc(itr.next()); var title:String = cd.Title; var artist:String = cd.Artist; trace("Title: " + title + " - Artist: " + artist); } }
Collection.getLength() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage collection.getLength() Returns
The number of items in the collection. Description
Method; returns the number of items in the collection. Example
The following example calls getLength(): //... var myColl:mx.utils.Collection; myColl = _parent.thisShelf.MyCompactDiscs; trace ("Collection size is: " + myColl.getLength()); //...
Collection interface (Flash Professional only)
173
Collection.isEmpty() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage collection.isEmpty() Returns
A Boolean value of true if the collection is empty. Description
Method; indicates whether the collection is empty. Example
The following example calls isEmpty(): on (click) { var myColl:mx.utils.Collection; myColl = _parent.thisShelf.MyCompactDiscs; if (myColl.isEmpty()) { trace("No CDs in the collection"); } } //...
Collection.removeItem() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage collection.removeItem(item) Parameters item
The object to be removed from the collection.
Returns
A Boolean value of true if item was removed successfully.
174
Chapter 6: Components Dictionary
Description
Method; removes the specified item from the collection. Because Collection.removeItem() dynamically reduces the size of the collection, do not call this method while looping through an iterator. Example
The following example calls removeItem(): var myColl:mx.utils.Collection; myColl = _parent.thisShelf.MyCompactDiscs; // get this from a text input box var removeArtist:String = _parent.tArtistToRemove.text; var removeSize:Number = 0; if (myColl.isEmpty()) { trace("No CDs in the collection"); } else { var toRemove:Array = new Array(); var itr:mx.utils.Iterator = myColl.getIterator(); var cd:CompactDisc = new CompactDisc(); var title:String = ""; var artist:String = ""; while (itr.hasNext()) { cd = CompactDisc(itr.next()); title = cd.Title; artist = cd.Artist; if(artist == removeArtist) { // mark this artist for deletion removeSize = toRemove.push(cd); trace("*** Marked for deletion: " + artist + "|" + title); } } // after while loop, remove the bad ones var removeCD:CompactDisc = new CompactDisc(); for(i = 0; i < removeSize; i++) { removeCD = toRemove[i]; trace("Removing: " + removeCD.Artist + "|" + removeCD.Title); myColl.removeItem(removeCD); } }
Collection interface (Flash Professional only)
175
ComboBox component
CHAPTER 6 Components Dictionary
A combo box allows a user to make a single selection from a drop-down list. A combo box can be static or editable. An editable combo box allows a user to enter text directly into a text field at the top of the list, as well as selecting an item from a drop-down list. If the drop-down list hits the bottom of the document, it opens up instead of down. The combo box is composed of three subcomponents: a Button component, a TextInput component, and a List component. When a selection is made in the list, the label of the selection is copied to the text field at the top of the combo box. It doesn’t matter if the selection is made with the mouse or the keyboard. A ComboBox component receives focus if you click the text box or the button. When a ComboBox component has focus and is editable, all keystrokes go to the text box and are handled according to the rules of the TextInput component (see “TextInput component” on page 742), with the exception of the following keys: Key
Description
Control+Down Opens the drop-down list and gives it focus. Arrow Shift+Tab
Moves focus to the previous object.
Tab
Moves focus to the next object.
When a ComboBox component has focus and is static, alphanumeric keystrokes move the selection up and down the drop-down list to the next item with the same first character. You can also use the following keys to control a static combo box: Key
Description
Control+Down Opens the drop-down list and gives it focus. Arrow
176
Control+Up Arrow
Closes the drop-down list, if open in the stand-alone and browser versions of Flash Player.
Down Arrow
Moves the selection down one item.
End
Selection moves to the bottom of the list.
Escape
Closes the drop-down list and returns focus to the combo box in Test Movie mode.
Enter
Closes the drop-down list and returns focus to the combo box.
Home
Moves the selection to the top of the list.
Page Down
Moves the selection down one page.
Page Up
Moves the selection up one page.
Shift+Tab
Moves focus to the previous object.
Tab
Moves focus to the next object.
Chapter 6: Components Dictionary
When the drop-down list of a combo box has focus, alphanumeric keystrokes move the selection up and down the drop-down list to the next item with the same first character. You can also use the following keys to control a drop-down list: Key
Description
Control+Up Arrow
If the drop-down list is open, focus returns to the text box and the drop-down list closes in the stand-alone and browser versions of Flash Player.
Down Arrow
Moves the selection down one item.
End
Moves the insertion point to the end of the text box.
Enter
If the drop-down list is open, focus returns to the text box and the drop-down list closes.
Escape
If the drop-down list is open, focus returns to the text box and the drop-down list closes in Test Movie mode.
Home
Moves the insertion point to the beginning of the text box.
Page Down
Moves the selection down one page.
Page Up
Moves the selection up one page.
Tab
Moves focus to the next object.
Shift+End
Selects the text from the insertion point to the End position.
Shift+Home
Selects the text from the insertion point to the Home position.
Shift+Tab
Moves focus to the previous object.
Up Arrow
Moves the selection up one item.
Note: The page size used by the Page Up and Page Down keys is one less than the number of items that fit in the display. For example, paging down through a ten-line drop-down list will show items 09, 9-18, 18-27, and so on, with one item overlapping per page.
For more information about controlling focus, see “Creating custom focus navigation” on page 50 or “FocusManager class” on page 419. A live preview of each ComboBox component instance on the Stage reflects changes made to parameters in the Property inspector or Component inspector during authoring. However, the drop-down list does not open in the live preview, and the first item displays as the selected item. When you add the ComboBox component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility: mx.accessibility.ComboBoxAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances you have of the component. For more information, see Chapter 17, “Creating Accessible Content,” in Using Flash.
ComboBox component
177
Using the ComboBox component You can use a ComboBox component in any form or application that requires a single choice from a list. For example, you could provide a drop-down list of states in a customer address form. You can use an editable combo box for more complex scenarios. For example, in an application that provides driving directions, you could use an editable combo box for a user to enter her origin and destination addresses. The drop-down list would contain her previously entered addresses. ComboBox parameters You can set the following authoring parameters for each ComboBox component instance in the Property inspector or in the Component inspector: editable determines if the ComboBox component is editable (true) or only selectable (false). The default value is false. labels populates
the ComboBox component with an array of text values.
data
associates a data value with each item in the ComboBox component. The data parameter is an array.
rowCount
sets the maximum number of items that can be displayed in the list. The default value
is 5. You can write ActionScript to set additional options for ComboBox instances using the methods, properties, and events of the ComboBox class. For more information, see “ComboBox class” on page 182. Creating an application with the ComboBox component The following procedure explains how to add a ComboBox component to an application while authoring. In this example, the combo box presents a list of cities to select from in its drop-down list. To create an application with the ComboBox component:
1. Drag a ComboBox component from the Components panel to the Stage. 2. Select the Transform tool and resize the component on the Stage.
The combo box can only be resized on the Stage during authoring. Typically, you would only change the width of a combo box to fit its entries. 3. Select the combo box and, in the Property inspector, enter the instance name comboBox. 4. In the Component inspector or Property inspector, do the following: ■
■
Enter Minneapolis, Portland, and Keene for the label parameter. Double-click the label parameter field to open the Values dialog box. Then click the plus sign to add items. Enter MN.swf, OR.swf, and NH.swf for the data parameter. These are imaginary SWF files that, for example, you could load when a user selects a city from the combo box.
178
Chapter 6: Components Dictionary
5. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code: function change(evt){ trace(evt.target.selectedItem.label); } comboBox.addEventListener("change", this);
The last line of code adds a change event handler to the ComboBox instance. For more information, see ComboBox.change. Customizing the ComboBox component You can transform a ComboBox component horizontally and vertically while authoring. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. If text is too long to fit in the combo box, the text is clipped to fit. You must resize the combo box while authoring to fit the label text. In editable combo boxes, only the button is the hit area—not the text box. For static combo boxes, the button and the text box constitute the hit area. The hit area responds by opening or closing the drop-down list. Using styles with the ComboBox component You can set style properties to change the appearance of a ComboBox component. If the name of a style property ends in “Color”, it is a color style property and behaves differently than noncolor style properties. For more information, see “Using styles to customize component color and text” on page 67. The combo box has two unique styles: openDuration and openEasing. Other styles are passed to the button, text box, and drop-down list of the combo box through those individual components, as follows:
• The button is a Button instance and uses its styles. (See “Using styles with the Button component” on page 133.)
• The text is a TextInput instance and uses its styles. (See “Using styles with the TextInput component” on page 744.)
• The drop-down list is an List instance and uses its styles. (See “Using styles with the List component” on page 453.) A ComboBox component uses the following styles: Style
Theme Description
themeColor
Halo
The base color scheme of a component. Possible values are "haloGreen", "haloBlue", and "haloOrange". The default value is "haloGreen".
backgroundColor
Both
The background color. The default color is white.
ComboBox component
179
Style
Theme Description
border styles
Both
The Button subcomponent uses two RectBorder instances for its borders and responds to the styles defined on that class. See “RectBorder class” on page 647. In the Halo theme, the ComboBox component uses a custom rounded border for the collapsed portion of the ComboBox. The colors of this portion of the ComboBox can be modified only through skinning. See “Using skins with the ComboBox component” on page 181.
color
Both
The text color. The default value is 0x0B333C for the Halo theme and blank for the Sample theme.
disabledColor
Both
The color for text when the component is disabled. The default color is 0x848384 (dark gray).
embedFonts
Both
Boolean value that indicates whether the font specified in fontFamily is an embedded font. This style must be set to true if fontFamily refers to an embedded font. Otherwise, the embedded font will not be used. If this style is set to true and fontFamily does not refer to an embedded font, no text will be displayed. The default value is false.
fontFamily
Both
The font name for text. The default value is "_sans".
fontSize
Both
The point size for the font. The default value is 10.
fontStyle
Both
The font style: either "normal" or "italic". The default value is "normal".
fontWeight
Both
The font weight: either "none" or "bold". The default value is "none". All components can also accept the value "normal" in place of "none" during a setStyle() call, but subsequent calls to getStyle() will return "none".
textAlign
Both
The text alignment: either "left", "right", or "center". The default value is "left".
textDecoration
Both
The text decoration: either "none" or "underline". The default value is "none".
openDuration
Both
The duration, in milliseconds, of the transition animation. The default value is 250.
openEasing
Both
A reference to a tweening function that controls the animation. Defaults to sine in/out. For more information, see “Customizing component animations” on page 75.
The following example demonstrates how to use List styles to control the behavior of the dropdown portion of a ComboBox component. // comboBox is an instance of the ComboBox component on Stage comboBox.setStyle("alternatingRowColors", [0xFFFFFF, 0xBFBFBF]);
180
Chapter 6: Components Dictionary
Using skins with the ComboBox component The ComboBox component uses symbols in the library to represent the button states and has skin variables for the down arrow. These skins are located in the Flash UI Components 2/ Themes/MMDefault/ComboBox Assets/States folder of the HaloTheme.fla and SampleTheme.fla files. The information below describes these skins and provides steps for customizing them. The ComboBox component also uses scroll bar skins for the drop-down list’s scroll bar and two RectBorder class instances for the border around the text input and drop-down list. For information on customizing these skins, see “Using skins with the UIScrollBar component” on page 831 and “RectBorder class” on page 647. For more information on the methods available to skin components, see “About skinning components” on page 80. A ComboBox component uses the following skin properties: Property
Description
ComboDownArrowDisabledName The down arrow’s disabled state. The default is ComboDownArrowDisabled. ComboDownArrowDownName
The down arrow’s down state. The default is ComboDownArrowDown.
ComboDownArrowUpName
The down arrow’s up state. The default is ComboDownArrowOver.
ComboDownArrowOverName
The down arrow’s over state. The default is ComboDownArrowUp.
To create movie clip symbols for ComboBox skins:
1. Create a new FLA file. 2. Select File > Import > Open External Library, and select the HaloTheme.fla file.
This file is located in the application-level configuration folder. For the exact location on your operating system, see “About themes” on page 77. 3. In the theme’s Library panel, expand the Flash UI Components 2/Themes/MMDefault folder
and drag the ComboBox Assets folder to the library for your document. 4. Expand the ComboBox Assets/States folder in the library of your document. 5. Open the symbols you want to customize for editing.
For example, open the ComboDownArrowDisabled symbol. 6. Customize the symbol as desired.
For example, change the inner white square to a light gray. 7. Repeat steps 5-6 for all symbols you want to customize. 8. Click the Back button to return to the main Timeline. 9. Drag a ComboBox component to the Stage. 10. Set the ComboBox instance properties as desired.
For this example, use ActionScript to set the ComboBox to disabled. 11. Select Control > Test Movie.
ComboBox component
181
ComboBox class Inheritance
MovieClip > UIObject class > UIComponent class > ComboBase > ComboBox
ActionScript Class Name
mx.controls.ComboBox
The ComboBox component combines three separate subcomponents: Button, TextInput, and List. Most of the methods, properties, and events of each subcomponent are available directly from the ComboBox component and are listed in the summary tables for the ComboBox class. The drop-down list in a combo box is provided either as an array or as a data provider. If you use a data provider, the list changes at runtime. You can change the source of the ComboBox data dynamically by switching to a new array or data provider. Items in a combo box list are indexed by position, starting with the number 0. An item can be one of the following:
• A primitive data type. • An object that contains a label property and a data property Note: An object may use the ComboBox.labelFunction or ComboBox.labelField property to determine the label property.
If the item is a primitive data type other than String, it is converted to a string. If an item is an object, the label property must be a string and the data property can be any ActionScript value. ComboBox methods to which you supply items have two parameters, label and data, that refer to the properties above. Methods that return an item return it as an object. A combo box defers the instantiation of its drop-down list until a user interacts with it. Therefore, a combo box may appear to respond slowly on first use. Use the following code to programmatically access the ComboBox component’s drop-down list and override the delay: var foo = myComboBox.dropdown;
Accessing the drop-down list may cause a pause in the application. This may occur when the user first interacts with the combo box, or when the above code runs. Method summary for the ComboBox class The following table lists methods of the ComboBox class.
182
Method
Description
ComboBox.addItem()
Adds an item to the end of the list.
ComboBox.addItemAt()
Adds an item to the end of the list at the specified index.
ComboBox.close()
Closes the drop-down list.
ComboBox.getItemAt()
Returns the item at the specified index.
ComboBox.open()
Opens the drop-down list.
ComboBox.removeAll()
Removes all items in the list.
Chapter 6: Components Dictionary
Method
Description
ComboBox.removeItemAt()
Removes an item from the list at the specified location.
ComboBox.replaceItemAt()
Replaces the content of the item at the specified index.
ComboBox.sortItems()
Sorts the list using a compare function.
ComboBox.sortItemsBy()
Sorts the list using a field of each item.
Methods inherited from the UIObject class
The following table lists the methods the ComboBox class inherits from the UIObject class. When calling these methods from the ComboBox object, use the form comboBoxInstance.methodName. Method
Description
UIObject.createClassObject() Creates an object on the specified class. UIObject.createObject()
Creates a subobject on an object.
UIObject.destroyObject()
Destroys a component instance.
UIObject.doLater()
Calls a function when parameters have been set in the Property and Component inspectors.
UIObject.getStyle()
Gets the style property from the style declaration or object.
UIObject.invalidate()
Marks the object so it will be redrawn on the next frame interval.
UIObject.move()
Moves the object to the requested position.
UIObject.redraw()
Forces validation of the object so it is drawn in the current frame.
UIObject.setSize()
Resizes the object to the requested size.
UIObject.setSkin()
Sets a skin in the object.
UIObject.setStyle()
Sets the style property on the style declaration or object.
Methods inherited from the UIComponent class
The following table lists the methods the ComboBox class inherits from the UIComponent class. When calling these methods from the ComboBox object, use the form comboBoxInstance.methodName. Method
Description
UIComponent.getFocus()
Returns a reference to the object that has focus.
UIComponent.setFocus()
Sets focus to the component instance.
ComboBox component
183
Property summary for the ComboBox class The following table lists properties of the ComboBox class. Property
Description
ComboBox.dataProvider
The data model for the items in the list.
ComboBox.dropdown
Returns a reference to the List component contained by the combo box.
ComboBox.dropdownWidth
The width of the drop-down list, in pixels.
ComboBox.editable
Indicates whether a combo box is editable.
ComboBox.labelField
Indicates which data field to use as the label for the drop-down list.
ComboBox.labelFunction
Specifies a function to compute the label field for the drop-down list.
ComboBox.length
Read-only; the length of the drop-down list.
ComboBox.restrict
The set of characters that a user can enter in the text field of a combo box.
ComboBox.rowCount
The maximum number of list items to display at one time.
ComboBox.selectedIndex
The index of the selected item in the drop-down list.
ComboBox.selectedItem
The value of the selected item in the drop-down list.
ComboBox.text
The string of text in the text box.
ComboBox.textField
A reference to the TextInput component in the combo box.
ComboBox.value
The value of the text box (editable) or drop-down list (static).
Properties inherited from the UIObject class
The following table lists the properties the ComboBox class inherits from the UIObject class. When accessing these properties from the ComboBox object, use the form comboBoxInstance.propertyName.
184
Property
Description
UIObject.bottom
The position of the bottom edge of the object, relative to the bottom edge of its parent. Read-only.
UIObject.height
The height of the object, in pixels. Read-only.
UIObject.left
The left edge of the object, in pixels. Read-only.
UIObject.right
The position of the right edge of the object, relative to the right edge of its parent. Read-only.
UIObject.scaleX
A number indicating the scaling factor in the x direction of the object, relative to its parent.
UIObject.scaleY
A number indicating the scaling factor in the y direction of the object, relative to its parent.
Chapter 6: Components Dictionary
Property
Description
UIObject.top
The position of the top edge of the object, relative to its parent. Read-only.
UIObject.visible
A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width
The width of the object, in pixels. Read-only.
UIObject.x
The left edge of the object, in pixels. Read-only.
UIObject.y
The top edge of the object, in pixels. Read-only.
Properties inherited from the UIComponent class
The following table lists the properties the ComboBox class inherits from the UIComponent class. When accessing these properties from the ComboBox object, use the form comboBoxInstance.propertyName. Property
Description
UIComponent.enabled
Indicates whether the component can receive focus and input.
UIComponent.tabIndex
A number indicating the tab order for a component in a document.
Event summary for the ComboBox class The following table lists events of the ComboBox class. Event
Description
ComboBox.change
Broadcast when the value of the combo box changes as a result of user interaction.
ComboBox.close
Broadcast when the list of the combo box begins to retract.
ComboBox.enter
Broadcast when the Enter key is pressed.
ComboBox.itemRollOut
Broadcast when the pointer rolls off a drop-down list item.
ComboBox.itemRollOver
Broadcast when a drop-down list item is rolled over.
ComboBox.open
Broadcast when the drop-down list begins to open.
ComboBox.scroll
Broadcast when the drop-down list is scrolled.
Events inherited from the UIObject class
The following table lists the events the ComboBox class inherits from the UIObject class. Event
Description
UIObject.draw
Broadcast when an object is about to draw its graphics.
UIObject.hide
Broadcast when an object’s state changes from visible to invisible.
UIObject.load
Broadcast when subobjects are being created.
UIObject.move
Broadcast when the object has moved.
ComboBox component
185
Event
Description
UIObject.resize
Broadcast when an object has been resized.
UIObject.reveal
Broadcast when an object’s state changes from invisible to visible.
UIObject.unload
Broadcast when the subobjects are being unloaded.
Events inherited from the UIComponent class
The following table lists the events the ComboBox class inherits from the UIComponent class. Event
A number 0 or greater that indicates the position at which to insert the item (the index of the new item).
index
A string that indicates the label for the new item.
label
The data for the item; it can be of any data type. This parameter is optional.
data obj
An object with label and data properties.
Returns
The index at which the item was added. Description
Method; adds a new item to the end of the list at the index specified by the index parameter. Indices greater than ComboBox.length are ignored. Example
The following code inserts an item at index 3, which is the fourth position in the combo box list (0 is the first position): myBox.addItemAt(3, "this is the fourth Item");
ComboBox.change Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage
Usage 1: on(change){ // your code here }
ComboBox component
187
Usage 2: listenerObject = new Object(); listenerObject.change = function(eventObject){ // your code here } comboBoxInstance.addEventListener("change", listenerObject) Description
Event; broadcast to all registered listeners when the ComboBox.selectedIndex or ComboBox.selectedItem property changes as a result of user interaction. The first usage example uses an on() handler and must be attached directly to a ComboBox instance. The keyword this, used in an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox instance myBox, sends “_level0.myBox” to the Output panel: on(change){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. Finally, you call addEventListener() (see EventDispatcher.addEventListener()) on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
The following example sends the instance name of the component that generated the change event to the Output panel: form.change = function(eventObj){ trace("Value changed to " + eventObj.target.value); } myCombo.addEventListener("change", form); See also EventDispatcher.addEventListener()
The following example closes the drop-down list of the myBox combo box: myBox.close(); See also ComboBox.open()
ComboBox.close Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage
Usage 1: on(close){ // your code here }
Usage 2: listenerObject = new Object(); listenerObject.close = function(eventObject){ // your code here } comboBoxInstance.addEventListener("close", listenerObject)
ComboBox component
189
Description
Event; broadcast to all registered listeners when the drop-down list of the combo box is fully retracted. The first usage example uses an on() handler and must be attached directly to a ComboBox instance. The keyword this, used in an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox instance myBox, sends “_level0.myBox” to the Output panel: on(close){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, close) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
The following example sends a message to the Output panel when the drop-down list begins to close: form.close = function(){ trace("The combo box has closed"); } myCombo.addEventListener("close", form); See also EventDispatcher.addEventListener()
Property; the data model for items viewed in a list. The value of this property can be an array or any object that implements the DataProvider API. The default value is []. The List component and the ComboBox component share the dataProvider property, and changes to this property are immediately available to both components. The List component, like other data-aware components, adds methods to the Array object’s prototype so that they conform to the DataProvider API (see DataProvider.as for details). Therefore, any array that exists at the same time as a list automatically has all the methods (addItem(), getItemAt(), and so on) needed for it to be the model of a list, and can be used to broadcast model changes to multiple components. If the array contains objects, the labelField or labelFunction property is accessed to determine what parts of the item to display. The default value is "label", so if such a field exists, it is chosen for display; if not, a comma-separated list of all fields is displayed. Note: If the array contains strings at each index, and not objects, the list is not able to sort the items and maintain the selection state. Any sorting will cause the selection to be lost.
Any instance that implements the DataProvider API is eligible as a data provider for a List component. This includes Flash Remoting RecordSet objects, Firefly DataSet components, and so on. Example
This example uses an array of strings to populate the drop-down list: comboBox.dataProvider = ["Ground Shipping","2nd Day Air","Next Day Air"];
This example creates a data provider array and assigns it to the dataProvider property: myDP = new Array(); list.dataProvider = myDP; for (var i=0; i
ComboBox.dropdown Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage myComboBox.dropdown
ComboBox component
191
Description
Property (read-only); returns a reference to the list contained by the combo box. The List subcomponent isn’t instantiated in the combo box until it needs to be displayed. However, when you access the dropdown property, the list is created. See also ComboBox.dropdownWidth
Property; the width limit of the drop-down list, in pixels. The default value is the width of the ComboBox component (the TextInput instance plus the SimpleButton instance). Example
The following code sets dropdownWidth to 150 pixels: myComboBox.dropdownWidth = 150; See also ComboBox.dropdown
Property; indicates whether the combo box is editable (true) or not (false). In an editable combo box, a user can enter values into the text box that do not appear in the drop-down list. If a combo box is not editable, you cannot enter text into the text box. The text box displays the text of the item in the list. The default value is false.
192
Chapter 6: Components Dictionary
Making a combo box editable clears the combo box text field. It also sets the selected index (and item) to undefined. To make a combo box editable and still retain the selected item, use the following code: var ix = myComboBox.selectedIndex; myComboBox.editable = true; // clears the text field myComboBox.selectedIndex = ix; // copies the label back into the text field Example
The following code makes myComboBox editable: myComboBox.editable = true;
ComboBox.enter Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage
Usage 1: on(enter){ // your code here }
Usage 2: listenerObject = new Object(); listenerObject.enter = function(eventObject){ // your code here } comboBoxInstance.addEventListener("enter", listenerObject) Description
Event; broadcast to all registered listeners when the user presses the Enter key in the text box. This event is a TextInput event that is broadcast only from editable combo boxes. For more information, see TextInput.enter. The first usage example uses an on() handler and must be attached directly to a ComboBox instance. The keyword this, used in an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox instance myBox, sends “_level0.myBox” to the Output panel: on(enter){ trace(this); }
ComboBox component
193
The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, enter) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
The following example sends a message to the Output panel when the drop-down list begins to close: form.enter = function(){ trace("The combo box enter event was triggered"); } myCombo.addEventListener("enter", form); See also EventDispatcher.addEventListener()
The index of the item to retrieve. The index must be a number greater than or equal to 0, and less than the value of ComboBox.length.
index
Returns
The indexed item object or value. The value is undefined if the index is out of range. Description
Method; retrieves the item at a specified index.
194
Chapter 6: Components Dictionary
Example
The following code displays the item at index position 4: trace(myBox.getItemAt(4).label);
ComboBox.itemRollOut Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage
Usage 1: on(itemRollOut){ // your code here }
Usage 2: listenerObject = new Object(); listenerObject.itemRollOut = function(eventObject){ // your code here } comboBoxInstance.addEventListener("itemRollOut", listenerObject) Event object
In addition to the standard properties of the event object, the itemRollOut event has an index property. The index is the number of the item that the pointer rolled out of. Description
Event; broadcast to all registered listeners when the pointer rolls out of drop-down list items. This is a List event that is broadcast from a combo box. For more information, see List.itemRollOut. The first usage example uses an on() handler and must be attached directly to a ComboBox instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox instance myBox, sends “_level0.myBox” to the Output panel: on(itemRollOut){ trace(this); }
ComboBox component
195
The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, itemRollOut) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. For more information, see “EventDispatcher class” on page 415. Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. Example
The following example sends a message to the Output panel that indicates the index of the item that the pointer rolled out of: form.itemRollOut = function (eventObj) { trace("Item #" + eventObj.index + " has been rolled out of."); } myCombo.addEventListener("itemRollOut", form); See also ComboBox.itemRollOver, EventDispatcher.addEventListener()
ComboBox.itemRollOver Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage
Usage 1: on(itemRollOver){ // your code here }
Usage 2: listenerObject = new Object(); listenerObject.itemRollOver = function(eventObject){ // your code here } comboBoxInstance.addEventListener("itemRollOver", listenerObject) Event object
In addition to the standard properties of the event object, the itemRollOver event has an index property. The index is the number of the item that the pointer rolled over.
196
Chapter 6: Components Dictionary
Description
Event; broadcast to all registered listeners when the mouse pointer rolls over drop-down list items. This is a List event that is broadcast from a combo box. For more information, see List.itemRollOver. The first usage example uses an on() handler and must be attached directly to a ComboBox instance. The keyword this, used in an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox instance myBox, sends “_level0.myBox” to the Output panel: on(itemRollOver){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, itemRollOver) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. For more information, see “EventDispatcher class” on page 415. Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. Example
The following example sends a message to the Output panel that indicates the index of the item that the pointer rolled over: form.itemRollOver = function (eventObj) { trace("Item #" + eventObj.index + " has been rolled over."); } myCombo.addEventListener("itemRollOver", form); See also ComboBox.itemRollOut, EventDispatcher.addEventListener()
ComboBox.labelField Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage myComboBox.labelField
ComboBox component
197
Description
Property; the name of the field in dataProvider array objects to use as the label field. This is a property of the List component that is available from a ComboBox component instance. For more information, see List.labelField. The default value is undefined. Example
The following example sets the dataProvider property to an array of strings and sets the labelField property to indicate that the name field should be used as the label for the drop-down list: myComboBox.dataProvider = [ {name:"Gary", gender:"male"}, {name:"Susan", gender:"female"} ]; myComboBox.labelField = "name"; See also List.labelFunction
Property; a function that computes the label of a data provider item. You must define the function. The default value is undefined. Example
The following example creates a data provider and then defines a function to specify what to use as the label in the drop-down list: myComboBox.dataProvider = [ {firstName:"Nigel", lastName:"Pegg", age:"really young"}, {firstName:"Gary", lastName:"Grossman", age:"young"}, {firstName:"Chris", lastName:"Walcott", age:"old"}, {firstName:"Greg", lastName:"Yachuk", age:"really old"} ]; myComboBox.labelFunction = function(itemObj){ return (itemObj.lastName + ", " + itemObj.firstName); }
Property (read-only); the length of the drop-down list. This is a property of the List component that is available from a ComboBox instance. For more information, see List.length. The default value is 0. Example
The following example stores the value of length to a variable: dropdownItemCount = myBox.length;
ComboBox.open() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage myComboBox.open() Parameters
None. Returns
Nothing. Description
Method; opens the drop-down list. Example
The following code opens the drop-down list for the combo1 instance: combo1.open();
ComboBox component
199
See also ComboBox.close()
ComboBox.open Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage
Usage 1: on(open){ // your code here }
Usage 2: listenerObject = new Object(); listenerObject.open = function(eventObject){ // your code here } comboBoxInstance.addEventListener("open", listenerObject) Description
Event; broadcast to all registered listeners when the drop-down list is completely open. The first usage example uses an on() handler and must be attached directly to a ComboBox instance. The keyword this, used in an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox instance myBox, sends “_level0.myBox” to the Output panel: on(open){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, open) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. For more information, see “EventDispatcher class” on page 415. Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.
200
Chapter 6: Components Dictionary
Example
The following example sends a message to the Output panel: function open(evt) { trace("The combo box has opened with text " + evt.target.text); } myBox.addEventListener("open", this); See also ComboBox.close, EventDispatcher.addEventListener()
Method; removes all items in the list. This is a method of the List component that is available from an instance of the ComboBox component. Example
The following code clears the list: myCombo.removeAll(); See also ComboBox.removeItemAt(), ComboBox.replaceItemAt()
ComboBox.removeItemAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004.
ComboBox component
201
Usage listInstance.removeItemAt(index) Parameters
A number that indicates the position of the item to remove. The index is zero-based.
index Returns
An object; the removed item (undefined if no item exists). Description
Method; removes the item at the specified index position. The list indices after the index indicated by the index parameter collapse by one. This is a method of the List component that is available from an instance of the ComboBox component. Example
The following code removes the item at index position 3: myCombo.removeItemAt(3); See also ComboBox.removeAll(), ComboBox.replaceItemAt()
A number 0 or greater that indicates the position at which to insert the item (the index of the new item).
index
label data obj
A string that indicates the label for the new item. The data for the item. This parameter is optional. An object with label and data properties.
Returns
Nothing.
202
Chapter 6: Components Dictionary
Description
Method; replaces the content of the item at the specified index. This is a method of the List component that is available from the ComboBox component. Example
The following example changes the third index position: myCombo.replaceItemAt(3, "new label"); See also ComboBox.removeAll(), ComboBox.removeItemAt()
Property; indicates the set of characters that a user can enter in the text field of a combo box. The default value is undefined. If this property is null or an empty string (""), a user can enter any character. If this property is a string of characters, the user can enter only characters in the string; the string is scanned from left to right. You can specify a range by using a dash (-). If the string begins with a caret (^), all characters that follow the caret are considered unacceptable characters. If the string does not begin with a caret, the characters in the string are considered acceptable. You can use the backslash (\) to enter a hyphen (-), caret (^), or backslash (\) character, as shown here: \^ \\\
When you enter a backslash in the Actions panel within double quotation marks, it has a special meaning for the Actions panel’s double-quote interpreter. It signifies that the character following the backslash should be treated “as is.” For example, you could use the following code to enter a single quotation mark: var leftQuote = "\’";
The Actions panel’s restrict interpreter also uses the backslash as an escape character. Therefore, you may think that the following should work: myText.restrict = "0-9\-\^\\";
ComboBox component
203
However, since this expression is surrounded by double quotation marks, the value 0-9-^\ is sent to the restrict interpreter, and the restrict interpreter doesn’t understand this value. Because you must enter this expression within double quotation marks, you must not only provide the expression for the restrict interpreter, but you must also escape the expression so that it will be read correctly by the Actions panel’s built-in interpreter for double quotation marks. To send the value 0-9\-\^\\ to the restrict interpreter, you must enter the following code: myCombo.restrict = "0-9\\-\\^\\\\";
The restrict property restricts only user interaction; a script may put any text into the text field. This property does not synchronize with the Embed Font Outlines check boxes in the Property inspector. Example
In the following example, the first line of code limits the text field to uppercase letters, numbers, and spaces. The second line of code allows all characters except lowercase letters. my_combo.restrict = "A-Z 0-9"; my_combo.restrict = "^a-z";
The following code allows a user to enter the characters “0 1 2 3 4 5 6 7 8 9 - ^ \” in the instance myCombo. You must use a double backslash to escape the characters -, ^, and \. The first \ escapes the double quotation marks, and the second \ tells the interpreter that the next character should not be treated as a special character. myCombo.restrict = "0-9\\-\\^\\\\";
Property; the maximum number of rows visible in the drop-down list. The default value is 5. If the number of items in the drop-down list is greater than the rowCount property, the list resizes and a scroll bar is displayed if necessary. If the drop-down list contains fewer items than the rowCount property, it resizes to the number of items in the list. This behavior differs from the List component, which always shows the number of rows specified by its rowCount property, even if some empty space is shown. If the value is negative or fractional, the behavior is undefined.
204
Chapter 6: Components Dictionary
Example
The following example specifies that the combo box should have 20 or fewer rows visible: myComboBox.rowCount = 20;
ComboBox.scroll Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage
Usage 1: on(scroll){ // your code here }
Usage 2: listenerObject = new Object(); listenerObject.scroll = function(eventObject){ // your code here } comboBoxInstance.addEventListener("scroll", listenerObject) Event object
Along with the standard event object properties, the scroll event has one additional property, direction. It is a string with two possible values, "horizontal" or "vertical". For a ComboBox scroll event, the value is always "vertical". Description
Event; broadcast to all registered listeners when the drop-down list is scrolled. This is a List component event that is available to the ComboBox component. The first usage example uses an on() handler and must be attached directly to a ComboBox instance. The keyword this, used in an on() handler attached to a component, refers to the instance. For example, the following code, attached to the ComboBox component instance myBox, sends “_level0.myBox” to the Output panel: on(scroll){ trace(this); }
ComboBox component
205
The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, scroll) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. For more information, see “EventDispatcher class” on page 415. Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. Example
The following example sends a message to the Output panel that indicates the index of the item that the list scrolled to: form.scroll = function (eventObj) { trace("The list had been scrolled to item # " + eventObj.target.vPosition); } myCombo.addEventListener("scroll", form); See also EventDispatcher.addEventListener()
Property; the index number of the selected item in the drop-down list. The default value is 0. Assigning this property clears the current selection, selects the indicated item, and displays the label of that item in the combo box’s text box. If you assign an out-of-range value to this property, Flash ignores it. Entering text into the text field of an editable combo box sets selectedIndex to undefined. Example
The following code selects the last item in the list: myComboBox.selectedIndex = myComboBox.length-1;
Property; the value of the selected item in the drop-down list. If the combo box is editable, selectedItem returns undefined if the user enters any text in the text box. The property only has a value if you select an item from the drop-down list or set the value using ActionScript. If the combo box is static, the value of selectedItem is always valid; it returns undefined if there are no items in the list. Example
The following example shows selectedItem if the data provider contains primitive types: var item = myComboBox.selectedItem; trace("You selected the item " + item);
The following example shows selectedItem if the data provider contains objects with label and data properties: var obj = myComboBox.selectedItem; trace("You have selected the color named: " + obj.label); trace("The hex value of this color is: " + obj.data); See also ComboBox.dataProvider, ComboBox.selectedIndex
ComboBox.sortItems() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage myComboBox.sortItems([compareFunc], [optionsFlag])
ComboBox component
207
Parameters compareFunc A reference to a function that compares two items to determine their sort order. For details, see Array.sort() in Flash ActionScript Language Reference. This parameter is optional. optionsFlag Lets you perform multiple sorts of different types on a single array without having to replicate the entire array or re-sort it repeatedly. This parameter is optional.
The following are possible values for optionsFlag:
• • •
Array.DESCENDING,
•
Array.UNIQUESORT, which returns an error code (0) instead of a sorted array if two objects in the array are identical or have identical sort fields.
•
Array.RETURNINDEXEDARRAY,
which sorts highest to lowest.
Array.CASEINSENSITIVE,
which sorts without regard to case.
Array.NUMERIC,
which sorts numerically if the two elements being compared are numbers. If they aren’t numbers, use a string comparison (which can be case-insensitive if that flag is specified).
which returns an integer index array that is the result of the sort. For example, the following array would return the second line of code and the array would remain unchanged:
["a", "d", "c", "b"] [0, 3, 2, 1]
You can combine these options into one value. For example, the following code combines options 3 and 1: array.sort (Array.NUMERIC | Array.DESCENDING) Returns
Nothing. Description
Method; sorts the items in the combo box according to the specified compare function or according to the specified sort options. Example
This example sorts according to uppercase labels. The items a and b are passed to the function and contain label and data fields: myComboBox.sortItems(upperCaseFunc); function upperCaseFunc(a,b){ return a.label.toUpperCase() rel="nofollow"> b.label.toUpperCase(); }
The following example uses the upperCaseFunc() function defined above, along with the optionsFlag parameter to sort the elements of a ComboBox instance named myComboBox: myComboBox.addItem("Mercury"); myComboBox.addItem("Venus"); myComboBox.addItem("Earth"); myComboBox.addItem("planet");
208
Chapter 6: Components Dictionary
myComboBox.sortItems(upperCaseFunc, Array.DESCENDING); // The resulting sort order of myComboBox will be: // Venus // planet // Mercury // Earth
ComboBox.sortItemsBy() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage myComboBox.sortItemsBy(fieldName, order [optionsFlag]) Parameters
A string that specifies the name of the field to use for sorting. This value is usually or "data".
fieldName "label"
A string that specifies whether to sort the items in ascending order ("ASC") or descending order ("DESC").
order
optionsFlag Lets you perform multiple sorts of different types on a single array without having to replicate the entire array or re-sort it repeatedly. This parameter is optional, but if used, should replace the order parameter.
The following are possible values for optionsFlag:
• • •
Array.DESCENDING,
•
Array.UNIQUESORT, which returns an error code (0) instead of a sorted array if two objects in the array are identical or have identical sort fields.
•
Array.RETURNINDEXEDARRAY,
which sorts highest to lowest.
Array.CASEINSENSITIVE,
which sorts without regard to case.
Array.NUMERIC,
which sorts numerically if the two elements being compared are numbers. If they aren’t numbers, use a string comparison (which can be case-insensitive if that flag is specified).
which returns an integer index array that is the result of the sort. For example, the following array would return the second line of code and the array would remain unchanged:
["a", "d", "c", "b"] [0, 3, 2, 1]
You can combine these options into one value. For example, the following code combines options 3 and 1: array.sort (Array.NUMERIC | Array.DESCENDING)
ComboBox component
209
Returns
Nothing. Description
Method; sorts the items in the combo box alphabetically or numerically, in the specified order, using the specified field name. If the fieldName items are a combination of text strings and integers, the integer items are listed first. The fieldName parameter is usually "label" or "data", but advanced programmers may specify any primitive value. If you want, you can use the optionsFlag parameter to specify a sorting style. Example
The following examples are based on a ComboBox instance named myComboBox, which contains four elements labeled "Apples", "Bananas", "cherries", and "Grapes": // First, populate the ComboBox with the elements. myComboBox.addItem("Bananas"); myComboBox.addItem("Apples"); myComboBox.addItem("cherries"); myComboBox.addItem("Grapes"); // The following statement sorts using the order parameter set to "ASC", // and results in a sort that places "cherries" at the bottom of the list // because the sort is case-sensitive. myDP.sortItemsBy("label", "ASC"); // resulting order: Apples, Bananas, Grapes, cherries // The following statement sorts using the order parameter set to "DESC", // and results in a sort that places "cherries" at the top of the list // because the sort is case-sensitive. myComboBox.sortItemsBy("label", "DESC"); // resulting order: cherries, Grapes, Bananas, Apples // The following statement sorts using the optionsFlag parameter set to // Array.CASEINSENSITIVE. Note that an ascending sort is the default setting. myComboBox.sortItemsBy("label", Array.CASEINSENSITIVE); // resulting order: Apples, Bananas, cherries, Grapes // The following statement sorts using the optionsFlag parameter set to // Array.CASEINSENSITIVE | Array.DESCENDING. myComboBox.sortItemsBy("label", Array.CASEINSENSITIVE | Array.DESCENDING); // resulting order: Grapes, cherries, Bananas, Apples
ComboBox.text Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004.
210
Chapter 6: Components Dictionary
Usage myComboBox.text Description
Property; the text of the text box. You can get and set this value for editable combo boxes. For static combo boxes, the value is read-only. Example
The following example sets the current text value of an editable combo box: myComboBox.text = "California";
Property (read-only); a reference to the TextInput component contained by the ComboBox component. This property lets you access the underlying TextInput component so that you can manipulate it. For example, you might want to change the selection of the text box or restrict the characters that can be entered in it. Example
The following code restricts the text box of myComboBox so that it only accept numbers: myComboBox.textField.restrict = "0-9";
ComboBox.value Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004. Usage myComboBox.value
ComboBox component
211
Description
Property (read-only); if the combo box is editable, value returns the value of the text box. If the combo box is static, value returns the value of the drop-down list. The value of the drop-down list is the data field, or, if the data field doesn’t exist, the label field. Example
The following example puts the data into the combo box by setting the dataProvider property. It then displays the value in the Output panel. Finally, it selects "California" and displays it in the text box. cb.dataProvider = [ {label:"Alaska", data:"AZ"}, {label:"California", data:"CA"}, {label:"Washington", data:"WA"}]; cb.editable = true; cb.selectedIndex = 1; trace('Editable value is "California": '+ cb.value); cb.editable = false; cb.selectedIndex = 1; trace('Non-editable value is "CA": '+ cb.value);
212
Chapter 6: Components Dictionary
CHAPTER 6 Components Dictionary
Data binding classes (Flash Professional only)
The data binding classes provide the runtime functionality for the data binding feature in Flash MX Professional 2004. You can visually create and configure data bindings in the Flash authoring environment by using the Bindings tab in the Component inspector, or you can programmatically create and configure bindings by using the classes in the mx.data.binding package. For an overview of data binding and how to visually create data bindings in the Flash authoring tool, see “Data binding (Flash Professional only)” in Using Flash. Making data binding classes available at runtime (Flash Professional only) To compile your SWF file, your library must contain SWC files that contain the byte code for the data binding classes and web service classes. If you create data bindings in Flash while authoring, the relevant component classes are automatically added to the library. If you work with data binding and web services at runtime, you must add the classes to your FLA file’s library. You can get these SWC files from the Classes common library. To add the SWC files to your library:
1. Select the Classes library (Window > Other Panels > Common Libraries > Classes). 2. Open the library for your document (Window > Library). 3. Drag the appropriate SWC files (DataBindingClasses, WebServiceClasses, or both) from the
Classes library into your document’s library. For more information on these classes, see “Binding class (Flash Professional only)” on page 214 and “Web service classes (Flash Professional only)” on page 842. Classes in the mx.data.binding package (Flash Professional only) The following table lists the classes in the mx.data.binding package: Class
Description
Binding class (Flash Professional only)
Creates a binding between two endpoints.
ComponentMixins class (Flash Professional only)
Adds data binding functionality to components.
CustomFormatter class (Flash Professional only)
The base class for creating custom formatter classes.
CustomValidator class (Flash Professional only)
The base class for creating custom validator classes.
DataType class (Flash Professional only)
Provides read and write access to data fields of a component property.
Data binding classes (Flash Professional only)
213
Class
Description
EndPoint class (Flash Professional only)
Defines the source or destination of a binding.
TypedValue class (Flash Professional only)
Contains a data value and information about the value’s data type.
Binding class (Flash Professional only) ActionScript Class Name
mx.data.binding.Binding
The Binding class defines an association between two endpoints, a source and a destination. It listens for changes to the source endpoint and copies the changed data to the destination endpoint each time the source changes. You can write custom bindings by using the Binding class (and supporting classes), or use the Bindings tab in the Component inspector. Note: To make this class available at runtime, you must include the data binding classes in your FLA document. For more information, see “Making data binding classes available at runtime (Flash Professional only)” on page 213.
For an overview of the classes in the mx.data.binding package, see “Classes in the mx.data.binding package (Flash Professional only)” on page 213. Method summary for the Binding class The following table lists the methods of the Binding class. Method
Description
Binding.execute()
Fetches the data from the source component, formats it, and assigns it to the destination component.
Constructor for the Binding class Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage new Binding(source, destination, [format], [isTwoWay]) Parameters
A source endpoint of the binding. This parameter is nominally of type mx.data.binding.EndPoint, but can be any ActionScript object that has the required Endpoint fields (see “EndPoint class (Flash Professional only)” on page 224).
source
214
Chapter 6: Components Dictionary
destination
The destination endpoint of the binding. This parameter is nominally of type
mx.data.binding.EndPoint, but can be any ActionScript object that has the required Endpoint
fields. format An optional object that contains formatting information. The object must have the following properties:
• •
cls
An ActionScript class that extends the class mx.data.binding.DataAccessor.
An object whose properties provide optional settings for the formatter class specified by cls. settings
An optional Boolean value that specifies whether the new Binding object is bidirectional (true) or not (false). The default value is false.
isTwoWay
Returns
Nothing. Description
Constructor; creates a new Binding object. You can bind data to any ActionScript object that has properties and emits events including, but not limited to, components. A binding object exists as long as the innermost movie clip contains both the source and destination components. For example, if movie clip named A contains components X and Y, and there is a binding between X and Y, then the binding is in effect as long as movie clip A exists. Note: It’s not necessary to retain a reference to the new Binding object. As soon as the Binding object is created, it immediately begins listening for “changed” events emitted by either endpoint. In some cases, however, you might want to save a reference to the new Binding object, so that you can call its execute() method at a later time (see Binding.execute()). Example
In this example, the text property of a TextInput component (src_txt) is bound to the text property of another TextInput component (dest_txt). When the src_txt text field loses focus (that is, when the focusOut event is generated), the value of its text property is copied into dest_txt.text. import mx.data.binding.*; var src = new EndPoint(); src.component = src_txt; src.property = "text"; src.event = "focusOut"; var dest= new EndPoint(); dest.component = dest_txt; dest.property = "text"; new Binding(src, dest);
The following example demonstrates how to create a Binding object that uses a custom formatter class. For more information, see “CustomFormatter class (Flash Professional only)” on page 217. import mx.data.binding.*; var src = new EndPoint();
Data binding classes (Flash Professional only)
215
src.component = src_txt; src.property = "text"; src.event = "focusOut"; var dest= new EndPoint(); dest.component = text_dest; dest.property = "text"; new Binding(src, dest, {cls: mx.data.formatters.Custom, settings: {classname: "com.mycompany.SpecialFormatter"}});
Binding.execute() Availability
Flash Player 6. Edition
Flash MX Professional 2004. Usage myBinding.execute([reverse]) Parameters
A Boolean value that specifies whether the binding should also be executed from the destination to the source (true), or only from the source to the destination (false). By default, this value is false.
reverse
Returns
A null value if the binding executed successfully; otherwise, the method returns an array of error message strings that describe the errors that prevented the binding from executing. Description
Method; fetches the data from the source component and assigns it to the destination component. If the binding uses a formatter, then the data is formatted before being assigned to the destination. This method also validates the data and causes either a valid or invalid event to be emitted by the destination and source components. Data is assigned to the destination even if it’s invalid, unless the destination is read-only. If the reverse parameter is set to true and the binding is two-way, then the binding is executed in reverse (from the destination to the source). Example
The following code, attached to a Button component instance, executes the binding in reverse (from the destination component to the source component) when the button is clicked. on(click) { _root.myBinding.execute(true); }
216
Chapter 6: Components Dictionary
CustomFormatter class (Flash Professional only) ActionScript Class Name
mx.data.binding.CustomFormatter
The CustomFormatter class defines two methods, format() and unformat(), that provide the ability to transform data values from a specific data type to String, and vice versa. By default, these methods do nothing; you must implement them in a subclass of mx.data.binding.CustomFormatter. To create your own custom formatter, you first create a subclass of CustomFormatter that implements format() and unformat() methods. You can then assign that class to a binding between components either by creating a new Binding object with ActionScript (see “Binding class (Flash Professional only)” on page 214), or by using the Bindings tab in the Component inspector. For information on assigning a formatter class using the Component inspector, see “Schema formatters” in Using Flash. You can also assign a formatter class to a component property on the Component inspector’s Schema tab. However, in that case, the formatter will be used only when the data is needed in the form of a string. In contrast, formatters assigned with the Bindings panel, or created with ActionScript, are used whenever when the binding is executed. For an example of writing and assigning a custom formatter using ActionScript, see “Sample custom formatter” on page 217. Note: To make this class available at runtime, you must include the data binding classes in your FLA document.
For an overview of the classes in the mx.data.binding package, see “Classes in the mx.data.binding package (Flash Professional only)” on page 213. Sample custom formatter The following example demonstrates how to create a custom formatter class and then apply it to a binding between two components by using ActionScript. In this example, the current value of a NumericStepper component (its value property) is bound to the current value of a TextInput component (its text property). The custom formatter class formats the current numeric value of the NumericStepper component (for example, 1, 2, or 3) as its English word equivalent (for example, “one”, “two”, or “three”) before assigning it to the TextInput component. To create and use a custom formatter:
1. In Flash MX Professional 2004, create a new ActionScript file. 2. Add the following code to the file: // NumberFormatter.as class NumberFormatter extends mx.data.binding.CustomFormatter { // Format a Number, return a String function format(rawValue) { var returnValue; var strArray = new Array('one', 'two', 'three'); var numArray = new Array(1, 2, 3); returnValue = 0; for (var i = 0; i<strArray.length; i++) {
Data binding classes (Flash Professional only)
217
if (rawValue == numArray[i]) { returnValue = strArray[i]; break; } } return returnValue; } // convert a formatted value, return a raw value function unformat(formattedValue) { var returnValue; var strArray = new Array('one', 'two', 'three'); var numArray = new Array(1, 2, 3); returnValue = "invalid"; for (var i = 0; i<strArray.length; i++) { if (formattedValue == strArray[i]) { returnValue = numArray[i]; break; } } return returnValue; } }
3. Save the ActionScript file as NumberFormatter.as. 4. Create a new Flash (FLA) document. 5. From the Components panel, drag a TextInput component to the Stage and name it textInput.
Then drag a NumericStepper component to the Stage and name it stepper. 6. Open the Timeline and select the first frame on Layer 1. 7. In the Actions panel, add the following code to the Actions panel: import mx.data.binding.*; var x:NumberFormatter; var customBinding = new Binding({component:stepper, property:"value", event:"change"}, {component:textInput, property:"text", event:"enter,change"}, {cls:mx.data.formatters.Custom, settings:{classname:"NumberFormatter"}});
The second line of code (var x:NumberFormatter) ensures that the byte code for your custom formatter class is included in the compiled SWF file. 8. Select Window > Panels > Other Panels > Classes to open the Classes library. 9. Open your document’s library by selecting Window > Library. 10. Drag DataBindingClasses from the Classes library to your document’s library.
This makes the data binding runtime classes available for your document. 11. Save the FLA file to the same folder that contains NumberFormatter.as. 12. Test the file (Control > Test Movie).
Click the buttons on the NumericStepper component and watch the contents of the TextInput component update.
218
Chapter 6: Components Dictionary
Method summary for the CustomFormatter class The following table lists the methods of the CustomFormatter class. Method
Description
CustomFormatter.format()
Converts from a raw data type to a new object.
CustomFormatter.unformat()
Converts from a string, or other data type, to a raw data type.
CustomFormatter.format() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage
This method is called automatically; you don’t invoke it directly. Parameters rawData
The data to be formatted.
Returns
A formatted value. Description
Method; converts from a raw data type to a new object. This method is not implemented by default. You must define it in your subclass of mx.data.binding.CustomFormatter. For more information, see “Sample custom formatter” on page 217. CustomFormatter.unformat() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage
This method is called automatically; you don’t invoke it directly. Parameters formattedData
The formatted data to convert back to the raw data type.
Data binding classes (Flash Professional only)
219
Returns
An unformatted value. Description
Method; converts from a string, or other data type, to the raw data type. This transformation should be the exact inverse transformation of CustomFormatter.format(). This method is not implemented by default. You must define it in your subclass of mx.data.binding.CustomFormatter. For more information, see “Sample custom formatter” on page 217. CustomValidator class (Flash Professional only) ActionScript Class Name
mx.data.binding.CustomValidator
You use the CustomValidator class when you want to perform custom validation of a data field contained by a component. To create a custom validator class, you first create a subclass of mx.data.binding.CustomValidator that implements a method named validate(). This method is automatically passed a value to be validated. For more information about how to implement this method, see CustomValidator.validate(). Next, you assign your custom validator class to a field of a component by using the Component inspector’s Schema tab. For an example of creating and using a custom validator class, see the Example section in the CustomValidator.validate() entry. To assign a custom validator:
1. In the Component inspector, select the Schema tab. 2. Select the field you want to validate, and then select Custom from the Data Type pop-up menu. 3. Select the Validation Options field (at the bottom of the Schema tab), and click the magnifying
glass icon to open the Custom Validation Settings dialog box. 4. In the ActionScript Class text box, enter the name of the custom validator class you created.
In order for the class you specify to be included in the published SWF file, it must be in the classpath. Note: To make this class available at runtime, you must include the data binding classes in your FLA document. .
For an overview of the classes in the mx.data.binding package, see “Classes in the mx.data.binding package (Flash Professional only)” on page 213.
220
Chapter 6: Components Dictionary
Method summary for the CustomValidator class The following table lists the methods of the CustomValidator class. Method
This method is called automatically; you don’t invoke it directly. Parameters value
The data to be validated; it can be of any type.
Returns
Nothing. Description
Method; called automatically to validate the data contained by the value parameter. You must implement this method in your subclass of CustomValidator; the default implementation does nothing. You can use any ActionScript code to examine and validate the data. If the data is not valid, this method should call this.validationError() with an appropriate message. You can call this.validationError() more than once if there are several validation problems with the data. Since validate() might be called repeatedly, avoid adding code that takes a long time to complete. Your implementation of this method should only check for validity, and then report any errors using CustomValidator.validationError(). Similarly, your implementation should not take any action as a result of the validation test, such as alerting the end user. Instead, create event listeners for valid and invalid events and alert the end user from those event listeners (see the example below). Example
The following procedure demonstrates how to create and use a custom validator class. The validate() method of the CustomValidator class OddNumbersOnly.as determines any value that is not an odd number to be invalid. The validation occurs whenever a change occurs in the value of a NumericStepper component, which is bound to the text property of a Label component.
Data binding classes (Flash Professional only)
221
To create and use a custom validator class:
1. In Flash MX Professional 2004, create a new ActionScript (AS) file. 2. Add the following code to the AS file: class OddNumbersOnly extends mx.data.binding.CustomValidator { public function validate(value) { // make sure the value is of type Number var n = Number(value); if (String(n) == "NaN") { this.validationError("'" + value + "' is not a number."); return; } // make sure the number is odd if (n % 2 == 0) { this.validationError("'" + value + "' is not an odd number."); return; } // data is OK, no need to do anything, just return } }
3. Save the AS file as OddNumbersOnly.as. Note: The name of the AS file must match the name of the class.
4. Create a new Flash (FLA) document. 5. Open the Components panel. 6. Drag a NumericStepper component from the Components panel to the Stage and name
it stepper. 7. Drag a Label component to the Stage and name it textLabel. 8. Drag a TextArea component to the Stage and name it status. 9. Select the NumericStepper component, and open the Component inspector. 10. Select the Bindings tab in the Component inspector, and click the Add Binding (+) button. 11. Select the Value property (the only one) in the Add Bindings dialog box, and click OK. 12. In the Component inspector, double-click Bound To in the Binding Attributes pane of the
Bindings tab to open the Bound To dialog box. 13. In the Bound To dialog box, select the Label component in the Component Path pane and its text
property in the Schema Location pane. Click OK.
14. Select the Label component on the Stage, and click the Schema tab in the Component
Inspector panel. 15. In the Schema Attributes pane, select Custom from the Data Type pop-up menu. 16. Double-click the Validation Options field in the Schema Attributes pane to open the Custom
Validation Settings dialog box. 17. In the ActionScript Class text box, enter OddNumbersOnly, which is the name of the
ActionScript class you created previously. Click OK.
222
Chapter 6: Components Dictionary
18. Open the Timeline and select the first frame on Layer 1. 19. Open the Actions panel. 20. Add the following code to the Actions panel: function dataIsInvalid(evt) { if (evt.property == "text") { status.text = evt.messages; } } function dataIsValid(evt) { if (evt.property == "text") { status.text = "OK"; } } textLabel.addEventListener("valid", dataIsValid); textLabel.addEventListener("invalid", dataIsInvalid);
21. Save the FLA file as OddOnly.fla to the same folder that contains OddNumbersOnly.as. 22. Test the SWF file (Control > Test Movie).
Click the arrows on the NumericStepper component to change its value. Notice the message that appears in the TextArea component when you choose even and odd numbers. CustomValidator.validationError() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage this.validationError(errorMessage) Note: This method can be invoked only from within a custom validator class; the keyword this refers to the current CustomValidator object. Parameters errorMessage
A string that contains the error message to be reported.
Returns
Nothing. Description
Method; called from the validate() method of your subclass of CustomValidator to report validation errors. If you don’t call validationError(), a valid event is generated when validate() finishes executing. If you call validationError() one or more times from within the validate(), an invalid event is generated after validate() returns.
Data binding classes (Flash Professional only)
223
Each message you pass to validationError() is available in the messages property of the event object that was passed to the invalid event handler. Example
See the Example section for CustomValidator.validate(). EndPoint class (Flash Professional only) ActionScript Class Name
mx.data.binding.EndPoint
The EndPoint class defines the source or destination of a binding. EndPoint objects define a constant value, component property, or particular field of a component property, from which you can get data, or to which you can assign data. They can also define an event, or list of events, that a Binding object listens for; when the specified event occurs, the binding executes. When you create a new binding with the Binding class constructor, you pass it two EndPoint objects: one for the source and one for the destination. new mx.data.binding.Binding(srcEndPoint, destEndPoint);
The EndPoint objects, srcEndPoint and destEndPoint, might be defined as follows: var srcEndPoint = new mx.data.binding.EndPoint(); var destEndPoint = new mx.data.binding.EndPoint(); srcEndPoint.component = source_txt; srcEndPoint.property = "text"; srcEndPoint.event = "focusOut"; destEndPoint.component = dest_txt; destEndPoint.property = "text";
In English, the above code means “When the source text field loses focus, copy the value of its text property into the text property of the destination text field.” You can also pass generic ActionScript objects to the Binding constructor, rather than passing explicitly constructed EndPoint objects. The only requirement is that the objects define the required EndPoint properties, component and property. The following code is equivalent to that shown above. var srcEndPoint = {component:source_txt, property:"text"}; var destEndPoint = {component:dest_txt, property:"text"}; new mx.data.binding.Binding(srcEndPoint, destEndPoint); Note: To make this class available at runtime, you must include the data binding classes in your FLA document.
For an overview of the classes in the mx.data.binding package, see “Classes in the mx.data.binding package (Flash Professional only)” on page 213.
224
Chapter 6: Components Dictionary
Property summary for the EndPoint class The following table lists the properties of the EndPoint class. Method
Description
EndPoint.component
A reference to a component instance.
EndPoint.constant
A constant value.
EndPoint.event
The name of an event, or array of event names, that the component will emit when the data changes.
EndPoint.location
The location of a data field within the property of the component instance.
EndPoint.property
The name of a property of the component instance specified by EndPoint.component.
Constructor for the EndPoint class Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage new EndPoint() Returns
Nothing. Description
Constructor; creates a new EndPoint object. Example
This example creates a new EndPoint object named source_obj and assigns values to its component and property properties: var source_obj = new mx.data.binding.EndPoint(); source_obj.component = myTextField; source_obj.property = "text";
EndPoint.component Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004.
Data binding classes (Flash Professional only)
225
Usage endPointObj.component Description
Property; a reference to a component instance. Example
This example assigns an instance of the List component (listBox1) as the component parameter of an EndPoint object. var sourceEndPoint = new mx.data.binding.EndPoint(); sourceEndPoint.component=listBox1;
EndPoint.constant Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage endPoint_src.constant Description
Property; a constant value assigned to an EndPoint object. This property can be applied only to EndPoint objects that are the source, not the destination, of a binding between components. The value can be of any data type that is compatible with the destination of the binding. If this property is specified, all other EndPoint properties for the specified EndPoint object are ignored. Example
In this example, the string constant value “hello” is assigned to an EndPoint object’s constant property: var sourceEndPoint = new mx.data.binding.EndPoint(); sourceEndPoint.constant="hello";
EndPoint.event Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage endPointObj.event
226
Chapter 6: Components Dictionary
Description
Property; specifies the name of an event, or an array of event names, generated by the component when data assigned to the bound property changes. When the event occurs, the binding executes. The specified event only applies to components that are used as the source of a binding, or as the destination of a two-way binding. For more information about creating two-way bindings, see “Binding class (Flash Professional only)” on page 214. Example
In this example, the text property of one TextInput (src_txt) component is bound to the same property of another TextInput component (dest_txt). The binding is executed when either the focusOut or enter event is emitted by the src_txt component. var source = {component:src_txt, property:"text", event:["focusOut", "enter"]}; var dest = {component:myTextArea, property:"text"}; var newBind = new mx.data.binding.Binding(source, dest);
EndPoint.location Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage endPointObj.location Description
Property; specifies the location of a data field within the property of the component instance. There are four ways to specify a location: as a string that contains an XPath expression, as a string that contains an ActionScript path, as an array of strings, or as an object. XPath expressions can only be used when the data is an XML object. (See Example 1 below.) For a list of supported XPath expressions, see “Adding bindings using path expressions” in Using Flash. For XML and ActionScript objects, you can also specify a string that contains an ActionScript path. An ActionScript path contains the names of fields separated by dots (for example, "a.b.c"). You can also specify an array of strings as a location. Each string in the array “drills down” another level of nesting. You can use this technique with both XML and ActionScript data. (See Example 2 below.) When used with ActionScript data, an array of strings is equivalent to use of an ActionScript path; that is, the array ["a","b","c"] is equivalent to "a.b.c".
Data binding classes (Flash Professional only)
227
If you specify an object as the location, the object must specify two properties: path and indices. The path property is an array of strings, as discussed above, except that one or more of the specified strings may be the special token "[n]". For each occurrence of this token in path, there must be a corresponding index item in indices. As the path is evaluated, the indices are used to index into arrays. The index item can be any EndPoint object. This type of location can be applied to ActionScript data only—not XML. (See Example 3 below.) Example
Example 1: This example uses an XPath expression to specify the location of a node named zip in an XML object: var sourceEndPoint = new mx.databinding.EndPoint(); var sourcObj=new Object(); sourceObj.xml=new XML("94103"); sourceEndPoint.component=sourceObj; sourceEndPoint.property="xml"; sourceEndPoint.location="/zip";//
Example 2: This example uses an array of strings to “drill down” to a nested movie clip property: var sourceEndPoint = new mx.data.binding.EndPoint(); // assume movieClip1.ball.position exists sourceEndPoint.component=movieClip1; sourceEndPoint.property="ball"; // access movieClip1.ball.position.x sourceEndPoint.location=["position","x"];
Example 3: This example shows how to use an object to specify the location of a data field in a complex data structure: var city=new Object(); city.theaters = [{theater: "t1", movies: [{name: "Good,Bad,Ugly"}, {name:"Matrix Reloaded"}]}, {theater: "t2", movies: [{name: "Gladiator"}, {name: "Catch me if you can"}]}]; var srcEndPoint = new EndPoint(); srcEndPoint.component=city; srcEndPoint.property="theaters"; srcEndPoint.location = {path: ["[n]","movies","[n]","name"], indices: [{constant:0},{constant:0}]};
EndPoint.property Availability
Flash Player 6 (6.0 79.0) Edition
Flash MX Professional 2004. Usage endPointObj.property
228
Chapter 6: Components Dictionary
Description
Property; specifies a property name of the component instance specified by EndPoint.component that contains the bindable data. Note: EndPoint.component and EndPoint.property must combine to form a valid ActionScript object/ property combination. Example
This example binds the text property of one TextInput component (text_1) to the same property in another TextInput component (text_2). var sourceEndPoint = {component:text_1, property:"text"}; var destEndPoint = {component:text_2, property:"text"}; new Binding(sourceEndPoint, destEndPoint);
ComponentMixins class (Flash Professional only) ActionScript Class Name
mx.data.binding.ComponentMixins
The ComponentMixins class defines properties and methods that are automatically added to any object that is the source or destination of a binding, or to any component that’s the target of a ComponentMixins.initComponent() method call. These properties and methods do not affect normal component functionality; rather, they add functionality that is useful with data binding. Note: To make this class available at runtime, you must include the data binding classes in your FLA document.
For an overview of the classes in the mx.data.binding package, see “Classes in the mx.data.binding package (Flash Professional only)” on page 213. Method summary for the ComponentMixins class The following table lists the methods of the ComponentMixins class. Method
Description
ComponentMixins.getField()
Returns an object for getting and setting the value of a field at a specific location in a component property.
ComponentMixins.initComponent()
Adds the ComponentMixins methods to a component.
ComponentMixins.refreshDestinations()
Executes all the bindings that have this object as the source endpoint.
ComponentMixins.refreshFromSources()
Executes all bindings that have this component as the destination endpoint.
ComponentMixins.validateProperty()
Checks to see if the data in the indicated property is valid.
Data binding classes (Flash Professional only)
229
ComponentMixins.getField() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage componentInstance.getField(propertyName, [location]) Parameters propertyName
A string that contains the name of a property of the specified component.
An optional parameter that indicates the location of a field within the component property. This is useful if propertyName specifies a complex data structure and you are interested in a particular field of that structure. The location property can take one of three forms:
location
• A string that contains an XPath expression. This is only valid for XML data structures. For a list of supported XPath expressions, see “Adding bindings using path expressions” in Using Flash.
• A string that contains field names, separated by dots—for example, "a.b.c". This form is permitted for any complex data (ActionScript or XML).
• An array of strings, where each string is a field name—for example, ["a",
"b", "c"].
This
form is permitted for any complex data (ActionScript or XML). Returns
A DataType object. Description
Method; returns a DataType object whose methods you can use to get or set the data value in the component property at the specified field location. For more information, see “DataType class (Flash Professional only)” on page 234. Example
This example uses the DataType.setAsString() method to set the value of a field located in a component’s property. In this case the property (results) is a complex data structure. import mx.data.binding.*; var field : DataType = myComponent.getField("results", "po.address.name1"); field.setAsString("Teri Randall"); See also DataType.setAsString()
230
Chapter 6: Components Dictionary
ComponentMixins.initComponent() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage mx.data.binding.ComponentMixins.initComponent(componentInstance) Parameters componentInstance
A reference to a component instance.
Returns
Nothing. Description
Method (static); adds all the ComponentMixins methods to the component specified by componentInstance. This method is called automatically for all components involved in a data binding. To make the ComponentMixins methods available for a component that is not involved in a data binding, you must explicitly call this method for that component. Example
The following code makes the ComponentMixins methods available to a DataSet component: mx.data.binding.ComponentMixins.initComponent(_root.myDataSet);
Flash MX Professional 2004. Usage componentInstance.refreshDestinations() Parameters
None. Returns
Nothing. Description
Method; executes all the bindings for which componentInstance is the source EndPoint object. This method lets you execute bindings whose sources do not emit a “data changed” event.
Data binding classes (Flash Professional only)
231
Example
The following example executes all the bindings for which the DataSet component instance named user_data is the source EndPoint object: user_data.refreshDestinations();
ComponentMixins.refreshFromSources() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage componentInstance.refreshFromSources() Parameters
None. Returns
Nothing. Description
Method; executes all bindings for which componentInstance is the destination EndPoint object. This method lets you execute bindings that have constant sources, or sources that do not emit a “data changed” event. Example
The following example executes all the bindings for which the ListBox component instance named cityList is the destination EndPoint object: cityList.refreshFromSources();
ComponentMixins.validateProperty() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage componentInstance.validateProperty(propertyName) Parameters propertyName
A string that contains the name of a property that belongs to
componentInstance.
232
Chapter 6: Components Dictionary
Returns
An array, or null. Description
Method; determines if the data in propertyName is valid based on the property’s schema settings. The property’s schema settings are those specified on the Schema tab in the Component Inspector panel. The method returns null if the data is valid; otherwise, it returns an array of error messages as strings. Validation applies only to fields that have schema information available. If a field is an object that contains other fields, each “child” field is validated, and so on, recursively. Each individual field dispatches a valid or invalid event, as necessary. For each data field contained by propertyName, this method dispatches valid or invalid events, as follows:
• If the value of the field is null, and is not required, the method returns null. No events are generated.
• If the value the field is null, and is required, an error is returned and an invalid event is generated.
• If the value of the field is not null and the field’s schema does not have a validator, the method returns null; no events are generated.
• If the value is not null and the field’s schema does define a validator, the data is processed by the validator object. If the data is valid, a valid event is generated and null is returned; otherwise, an invalid event is generated and an array of error strings is returned. Example
The following example shows how to use validateProperty() to make sure that text entered by a user is of a valid length. You’ll determine the valid length by setting the Validation Options for the String data type in the Component inspector’s Schema tab. If the user enters a string of invalid length in the text field, the error messages returned by validateProperty() are displayed in the Output panel. To validate text entered by a user in a TextInput component:
1. Drag a TextInput component from the Components panel to the Stage, and name it
zipCode_txt. 2. Select the TextInput component and, in the Component inspector, click the Schema tab. 3. In the Schema Tree pane (the top pane of the Schema tab), select the text property. 4. In the Schema Attributes pane (the bottom pane of the Schema tab), select ZipCode from the
Data Type pop-up menu. 5. Open the Timeline if it is not already open. 6. Click the first frame on Layer 1 in the Timeline, and open the Actions panel (Window >
Development Panels > Actions).
Data binding classes (Flash Professional only)
233
7. Add the following code to the Actions panel: // Add ComponentMixin methods to TextInput component. // Note that this step is only necessary if the component // isn’t already involved in a data binding, // either as the source or destination. mx.data.binding.ComponentMixins.initComponent(zipCode_txt); // Define event listener function for component: validateResults = function (eventObj) { var errors:Array = eventObj.target.validateProperty("text"); if (errors != null) { trace(errors); } }; // Register listener function with component: zipCode_txt.addEventListener("enter", validateResults);
8. Select Window > Other Panels > Common Libraries > Classes to open the Classes library. 9. Open your document’s library by choosing Window > Library. 10. Drag DataBindingClasses from the Classes library to your document’s library.
This step makes the data binding runtime classes available to the SWF file at runtime. 11. Test the SWF file by selecting Control > Test Movie.
In the TextInput component on the Stage, enter an invalid United States zip code—for example, one that contains all letters, or one that contains fewer than five numbers. Notice the error messages displayed in the Output panel. DataType class (Flash Professional only) ActionScript Class Name
mx.data.binding.DataType
The DataType class provides read and write access to data fields of a component property. To get a DataType object, you call the ComponentMixins.getField() method on a component. You can then call methods of the DataType object to get and set the value of the field. If you get and set field values directly on the component instance instead of using DataType class methods, the data is provided in its “raw” form. In contrast, when you get or set field values using DataType methods, the values are processed according to the field’s schema settings. For example, the following code gets the value of a component’s property directly and assigns it to a variable. The variable, propVar, contains whatever “raw” value is the current value of the property propName. var propVar = myComponent.propName;
The next example gets the value of the same property by using the DataType.getAsString() method. In this case, the value assigned to stringVar is the value of propName after being processed according to its schema settings, and then returned as a string. var dataTypeObj:mx.data.binding.DataType = myComponent.getField("propName"); var stringVar: String = dataTypeObj.getAsString();
For more information about how to specify a field’s schema settings, see “Working with schemas in the Schema tab (Flash Professional only)” in Using Flash.
234
Chapter 6: Components Dictionary
You can also use the methods of the DataType class to get or set fields in various data types. The DataType class automatically converts the raw data to the requested type, if possible. For example, in the code example above, the data that’s retrieved is converted to the String type, even if the raw data is a different type. The ComponentMixins.getField() method is available for components that have been included in a data binding (either as a source, destination, or an index), or that have been initialized with ComponentMixins.initComponent(). For more information, see “ComponentMixins class (Flash Professional only)” on page 229. Note: To make this class available at runtime, you must include the data binding classes in your FLA document.
For an overview of the classes in the mx.data.binding package, see “Classes in the mx.data.binding package (Flash Professional only)” on page 213. Method summary for the DataType class The following table lists the methods of the DataType class. Method
Description
DataType.getAnyTypedValue() Fetches the current value of the field. DataType.getAsBoolean()
Fetches the current value of the field as a Boolean value.
DataType.getAsNumber()
Fetches the current value of the field as a number.
DataType.getAsString()
Fetches the current value of the field as a String value.
DataType.getTypedValue()
Fetches the current value of the field in the form of the requested data type.
DataType.setAnyTypedValue() Sets a new value in the field. DataType.setAsBoolean()
Sets the field to the new value, which is given as a Boolean value.
DataType.setAsNumber()
Sets the field to the new value, which is given as a number.
DataType.setAsString()
Sets the field to the new value, which is given as a string.
DataType.setTypedValue()
Sets a new value in the field.
Property summary for the DataType class The following table lists the properties of the DataType class. Property
Description
DataType.encoder
Provides a reference to the encoder object associated with this field.
DataType.formatter
Provides a reference to the formatter object associated with this field.
DataType.kind
Provides a reference to the Kind object associated with this field.
Data binding classes (Flash Professional only)
235
DataType.encoder Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.encoder Description
Property; provides a reference to the encoder object associated with this field, if one exists. You can use this property to access any properties and methods defined by the specific encoder applied to the field in the Component inspector’s Schema tab. If no encoder was applied to the field in question, then this property returns undefined. For more information about the encoders provided with Flash MX Professional 2004, see “Schema encoders” in Using Flash. Example
The following example assumes that the field being accessed (isValid) uses the Boolean encoder (mx.data.encoders.Bool). This encoder is provided with Flash MX Professional 2004 and contains a property named trueStrings that specifies which strings should be interpreted as true values. The code below sets the trueStrings property for a field’s encoder to be the strings “Yes” and “Oui”. var myField:mx.data.binding.DataType = dataSet.getField("isValid"); myField.encoder.trueStrings = "Yes,Oui";
DataType.formatter Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.formatter Description
Property; provides a reference to the formatter object associated with this field, if one exists. You can use this property to access any properties and methods for the formatter object applied to the field in the Component inspector’s Schema tab. If no formatter was applied to the field in question, this property returns undefined.
236
Chapter 6: Components Dictionary
For more information about the formatters provided with Flash MX Professional 2004, see “Schema formatters” in Using Flash. Example
This example assumes that the field being accessed is using the Number Formatter (mx.data.formatters.NumberFormatter) provided with Flash MX Professional 2004. This formatter contains a property named precision that specifies how many digits to display after the decimal point. This code sets the precision property to two decimal places for a field using this formatter. var myField:DataType = dataGrid.getField("currentBalance"); myField.formatter.precision = 2;
DataType.getAnyTypedValue() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.getAnyTypedValue(suggestedTypes) Parameters
An array of strings that specify, in descending order of desirability, the preferred data types for the field.
suggestedTypes
Returns
The current value of the field, in the form of one of the data types specified in the suggestedTypes array. Description
Method; fetches the current value of the field, using the information in the field’s schema to process the value. If the field can provide a value as the first data type specified in the suggestedTypes array, the method returns the field’s value as that data type. If not, the method attempts to extract the field’s value as the second data type specified in the suggestedTypes array, and so on. If you specify null as one of the items in the suggestedTypes array, the method returns the value of the field in the data type specified in the Schema tab of the Component inspector. Specifying null always results in a value being returned, so only use null at the end of the array. If a value can’t be returned in the form of the one of the suggested types, it is returned in the type specified in the Schema tab.
Data binding classes (Flash Professional only)
237
Example
This example attempts to get the value of a field (productInfo.available) in an XMLConnector component’s results property first as a number or, if that fails, as a string. import import var f: var b:
Flash MX Professional 2004. Usage dataTypeObject.getAsBoolean() Parameters
None. Returns
A Boolean value. Description
Method; fetches the current value of the field and converts it to Boolean form, if necessary. Example
In this example, a field named propName that belongs to a component named myComponent is retrieved as a Boolean value, and assigned to a variable: var dataTypeObj:mx.data.binding.DataType = myComponent.getField("propName"); var propValue:Boolean = dataTypeObj.getAsBoolean();
DataType.getAsNumber() Availability
Flash Player 6. Edition
Flash MX Professional 2004. Usage dataTypeObject.getAsNumber()
238
Chapter 6: Components Dictionary
Parameters
None. Returns
A number. Description
Method; fetches the current value of the field and converts it to Number form, if necessary. Example
In this example, a field named propName that belongs to a component named myComponent is retrieved as a number, and assigned to a variable: var dataTypeObj:mx.data.binding.DataType = myComponent.getField("propName"); var propValue:Number = dataTypeObj.getAsNumber(); See also DataType.getAnyTypedValue()
DataType.getAsString() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.getAsString() Parameters
None. Returns
A string. Description
Method; fetches the current value of the field and converts it to String form, if necessary. Example
In this example, a property named propName that belongs to a component named myComponent is retrieved as a string and assigned to a variable: var dataTypeObj:mx.data.binding.DataType = myComponent.getField("propName"); var propValue:String = dataTypeObj.getAsString(); See also DataType.getAnyTypedValue()
Data binding classes (Flash Professional only)
239
DataType.getTypedValue() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.getTypedValue(requestedType) Parameters requestedType
A string containing the name of a data type, or null.
Returns
A TypedValue object (see “TypedValue class (Flash Professional only)” on page 244). Description
Method; returns the value of the field in the specified form, if the field can provide its value in that form. If the field cannot provide its value in the requested form, the method returns null. If null is specified as requestedType, the method returns the value of the field in its default type. Example
The following example returns the value of the field converted to the Boolean data type. This is stored in the bool variable. var bool:TypedValue = field.getTypedValue("Boolean");
DataType.kind Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.kind Description
Property; provides a reference to the Kind object associated with this field. You can use this property to access properties and methods of the Kind object.
240
Chapter 6: Components Dictionary
DataType.setAnyTypedValue() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.setAnyTypedValue(newTypedValue) Parameters
A TypedValue object value to set in the field. For more information, see “TypedValue class (Flash Professional only)” on page 244.
newTypedValue
Returns
An array of strings describing any errors that occurred while attempting to set the new value. Errors can occur under any of the following conditions:
• The data provided cannot be converted to the data type of this field (for example, "abc" cannot be converted to Number).
• The data is an acceptable type but does not meet the validation criteria of the field. • The field is read-only. Note: The actual text of an error message varies depending on the data type, formatters, and encoders that are defined in the field’s schema. Description
Method; sets a new value in the field, using the information in the field’s schema to process the field. This method operates by first calling DataType.setTypedValue() to set the value. If that fails, the method checks to see if the destination object is willing to accept String, Boolean, or Number data, and if so, attempts to use the corresponding ActionScript conversion functions. Example
This example creates a new TypedValue object (a Boolean), and then assigns that value to a DataType object named field. Any errors that occur are assigned to the errors array. import mx.data.binding.*; var t:TypedValue = new TypedValue (true, "Boolean"); var errors: Array = field.setAnyTypedValue (t); See also DataType.setTypedValue()
Data binding classes (Flash Professional only)
241
DataType.setAsBoolean() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.setAsBoolean(newBooleanValue) Parameters newBooleanValue
A Boolean value.
Returns
Nothing. Description
Method; sets the field to the new value, which is given as a Boolean value. The value is converted to, and stored as, the data type that is appropriate for this field. Example
The following example sets a variable named bool to the Boolean value true. It then sets the value referenced by field to true. var bool: Boolean = true; field.setAsBoolean (bool);
DataType.setAsNumber() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.setAsNumber(newNumberValue) Parameters newNumberValue
A number.
Returns
Nothing. Description
Method; sets the field to the new value, which is given as a number. The value is converted to, and stored as, the data type that is appropriate for this field.
242
Chapter 6: Components Dictionary
Example
The following example sets a variable named num to the Number value of 32. It then sets the value referenced by field to num. var num: Number = 32; field.setAsNumber (num);
DataType.setAsString() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.setAsString(newStringValue) Parameters newStringValue
A string.
Returns
Nothing. Description
Method; sets the field to the new value, which is given as a string. The value is converted to, and stored as, the data type that is appropriate for this field. Example
The following example sets the variable stringVal to the string "The new value". It then sets the value of field to the string. var stringVal: String = "The new value"; field.setAsString (stringVal);
DataType.setTypedValue() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataTypeObject.setTypedValue(newTypedValue) Parameters newTypedValue
A TypedValue object value to set in the field.
Data binding classes (Flash Professional only)
243
For more information about TypedValue objects, see “TypedValue class (Flash Professional only)” on page 244. Returns
An array of strings describing any errors that occurred while attempting to set the new value. Errors can occur under any of the following conditions:
• The data provided is not an acceptable type. • The data provided cannot be converted to the data type of this field (for example, "abc" cannot be converted to Number).
• The data is an acceptable type but does not meet the validation criteria of the field. • The field is read-only. Note: The actual text of an error message varies depending on the data type, formatters, and encoders that are defined in the field’s schema. Description
Method; sets a new value in the field, using the information in the field’s schema to process the field. This method behaves similarly to DataType.setAnyTypedValue(), except that it doesn’t try as hard to convert the data to an acceptable data type. For more information, see DataType.setAnyTypedValue(). Example
This example creates a new TypedValue object (a Boolean), and then assigns that value to a DataType object named field. Any errors that occur are assigned to the errors array. import mx.data.binding.*; var bool:TypedValue = new TypedValue (true, "Boolean"); var errors: Array = field.setTypedValue (bool); See also DataType.setTypedValue()
TypedValue class (Flash Professional only) ActionScript Class Name
mx.data.binding.TypedValue
A TypedValue object contains a data value, along with information about the value’s data type. TypedValue objects are provided as parameters to, and are returned from, various methods of the DataType class. The data type information in the TypedValue object helps DataType objects decide when and how they need to do type conversion. Note: To make this class available at runtime, you must include the data binding classes in your FLA document.
For an overview of the classes in the mx.data.binding package, see “Classes in the mx.data.binding package (Flash Professional only)” on page 213.
244
Chapter 6: Components Dictionary
Property summary for the TypedValue class The following table lists the properties of the TypedValue class. Property
Description
TypedValue.type
Contains the schema associated with the TypedValue object’s value.
TypedValue.typeName
Names the data type of the TypedValue object’s value.
TypedValue.value
Contains the data value of the TypedValue object.
Constructor for the TypedValue class Availability
Flash Player 6 (6.0 79.0). Usage new mx.data.binding.TypedValue(value, typeName, [type]) Parameters value
A data value of any type.
typeName
A string that contains the name of the value’s data type.
An optional Schema object that describes in more detail the schema of the data. This field is required only in certain circumstances, such as when setting data into a DataSet component’s dataProvider property. type
Description
Constructor; creates a new TypedValue object. TypedValue.type Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage typedValueObject.type Description
Property; contains the schema associated with the TypedValue object’s value. Example
This example displays null in the Output panel: var t: TypedValue = new TypedValue (true, "Boolean", null); trace(t.type);
Data binding classes (Flash Professional only)
245
TypedValue.typeName Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage typedValueObject.typeName Description
Property; contains the name of the data type of the TypedValue object’s value. Example
This example displays Boolean in the Output panel: var t: TypedValue = new TypedValue (true, "Boolean", null); trace(t.typeName);
TypedValue.value Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage typedValueObject.value Description
Property; contains the data value of the TypedValue object. Example
This example displays true in the Output panel: var t: TypedValue = new TypedValue (true, "Boolean", null); trace(t.value);
246
Chapter 6: Components Dictionary
CHAPTER 6 Components Dictionary
DataGrid component (Flash Professional only)
The DataGrid component lets you create powerful data-enabled displays and applications. You can use the DataGrid component to instantiate a recordset (retrieved from a database query in Macromedia ColdFusion, Java, or .Net) using Macromedia Flash Remoting and display it in columns. You can also use data from a data set or from an array to fill a DataGrid component. The version 2 DataGrid component has been improved to include horizontal scrolling, better event support (including event support for editable cells), enhanced sorting capabilities, and performance optimizations. You can resize and customize characteristics such as the font, color, and borders of columns in a grid. You can use a custom movie clip as a “cell renderer” for any column in a grid. (A cell renderer displays the contents of a cell.) You can use scroll bars to move through data in a grid; you can also turn off scroll bars and use the DataGrid methods to create a page view style display. When you add the DataGrid component to an application, you can use the Accessibility panel to make the component accessible to screen readers. First, you must add the following line of code to enable accessibility for the DataGrid component: mx.accessibility.DataGridAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances you have of the component. For more information, see Chapter 17, “Creating Accessible Content,” in Using Flash. Interacting with the DataGrid component (Flash Professional only) You can use the mouse and the keyboard to interact with a DataGrid component. If DataGrid.sortableColumns and DataGridColumn.sortOnHeaderRelease are both true, clicking in a column header causes the grid to sort based on the column’s cell values. If DataGrid.resizableColumns is true, clicking in the area between columns lets you resize columns. Clicking in an editable cell sends focus to that cell; clicking a non-editable cell has no effect on focus. An individual cell is editable when both the DataGrid.editable and DataGridColumn.editable properties of the cell are true. When a DataGrid instance has focus either from clicking or tabbing, you can use the following keys to control it: Key
Description
Down Arrow
When a cell is being edited, the insertion point shifts to the end of the cell’s text. If a cell is not editable, the Down Arrow key handles selection as the List component does.
Up Arrow
When a cell is being edited, the insertion point shifts to the beginning of the cell’s text. If a cell is not editable, the Up Arrow key handles selection as the List component does.
Right Arrow
When a cell is being edited, the insertion point shifts one character to the right. If a cell is not editable, the Right Arrow key does nothing.
DataGrid component (Flash Professional only)
247
Key
Description
Left Arrow
When a cell is being edited, the insertion point shifts one character to the left. If a cell is not editable, the Left Arrow key does nothing.
Return/Enter/Shift+Enter When a cell is editable, the change is committed, and the insertion point is moved to the cell on the same column, next row (up or down, depending on the shift toggle). Shift+Tab/Tab
Moves focus to the previous item. When the Tab key is pressed, focus cycles from the last column in the grid to the first column on the next line. When Shift+Tab is pressed, cycling is reversed. All the text in the focused cell is selected.
Using the DataGrid component (Flash Professional only) You can use the DataGrid component as the foundation for numerous types of data-driven applications. You can easily display a formatted tabular view of a database query (or other data), but you can also use the cell renderer capabilities to build more sophisticated and editable user interface pieces. The following are practical uses for the DataGrid component:
• A webmail client • Search results pages • Spreadsheet applications such as loan calculators and tax form applications Understanding the design of the DataGrid component The DataGrid component extends the List component. When you design an application with the DataGrid component, it is helpful to understand how the List class underlying it was designed. The following are some fundamental assumptions and requirements that Macromedia used when developing the List class:
• Keep it small, fast, and simple. Don’t make something more complicated than absolutely necessary. This was the prime design directive. Most of the requirements listed below are based on this directive.
• Lists have uniform row heights. Every row must be the same height; the height can be set during authoring or at runtime.
• Lists must scale to thousands of records. • Lists don’t measure text. This creates a horizontal scrolling issue for List and Tree components; for more information, see “Understanding the design of the List component” on page 451. The DataGrid component, however, supports "auto" as an hScrollPolicy value, because it measures columns (which are the same width per item), not text. The fact that lists don’t measure text explains why lists have uniform row heights. Sizing individual rows to fit text would require intensive measuring. For example, if you wanted to accurately show the scroll bars on a list with nonuniform row height, you’d need to premeasure every row.
248
Chapter 6: Components Dictionary
• Lists perform worse as a function of their visible rows. Although lists can display 5000 records, they can’t render 5000 records at once. The more visible rows (specified by the rowCount property) you have on the Stage, the more work the list must to do to render. Limiting the number of visible rows, if at all possible, is the best solution.
• Lists aren’t tables. DataGrid components are intended to provide an interface for many records. They’re not designed to display complete information; they’re designed to display enough information so that users can drill down to see more. The message view in Microsoft Outlook is a prime example. You don’t read the entire e-mail in the grid; the message would be difficult to read and the client would perform terribly. Outlook displays enough information so that a user can drill into the post to see the details. Understanding the DataGrid component: data model and view Conceptually, the DataGrid component is composed of a data model and a view that displays the data. The data model consists of three main parts:
• DataProvider This is a list of items with which to fill the data grid. Any array in the same frame as a DataGrid component is automatically given methods (from the DataProvider API) that let you manipulate data and broadcast changes to multiple views. Any object that implements the DataProvider API can be assigned to the DataGrid.dataProvider property (including recordsets, data sets, and so on). The following code creates a data provider called myDP: myDP = new Array({name:"Chris", price:"Priceless"}, {name:"Nigel", price:"Cheap"});
• Item This is an ActionScript object used for storing the units of information in the cells of a column. A data grid is really a list that can display more than one column of data. A list can be thought of as an array; each indexed space of the list is an item. For the DataGrid component, each item consists of fields. In the following code, the content between curly braces ({}) is an item: myDP = new Array({name:"Chris", price:"Priceless"}, {name:"Nigel", price:"Cheap"});
• Field Identifiers that indicate the names of the columns within the items. This corresponds to the columnNames property in the columns list. In the List component, the fields are usually label and data, but in the DataGrid component the fields can be any identifier. In the following code, the fields are name and price: myDP = new Array({name:"Chris", price:"Priceless"}, {name:"Nigel", price:"Cheap"});
DataGrid component (Flash Professional only)
249
The view consists of three main parts:
• Row This is a view object responsible for rendering the items of the grid by laying out cells. Each row is laid out horizontally below the previous one.
• Column Columns are fields that are displayed in the grid; the fields each correspond to the columnName property of each column. Each column is a view object (an instance of the DataGridColumn class) responsible for displaying each column—for example, width, color, size, and so on. There are three ways to add columns to a data grid: assign a DataProvider object to (this automatically generates a column for each field in the first item), set DataGrid.columnNames to specify which fields will be displayed, or use the constructor for the DataGridColumn class to create columns and call DataGrid.addColumn() to add them to the grid. DataGrid.dataProvider
To format columns, either set up style properties for the entire data grid, or define DataGridColumn objects, set up their style formats individually, and add them to the data grid.
• Cell This is a view object responsible for rendering the individual fields of each item. To communicate with the data grid, these components must implement the CellRenderer API (see “CellRenderer API” on page 145). For a basic data grid, a cell is a built-in ActionScript TextField object. DataGrid parameters You can set the following authoring parameters for each DataGrid component instance in the Property inspector or in the Component inspector: multipleSelection is a Boolean value that indicates whether multiple items can be selected (true) or not (false). The default value is false. rowHeight indicates the height of each row, in pixels. Changing the font size does not change the
row height. The default value is 20. editable
is a Boolean value that indicates whether the grid is editable (true) or not (false). The default value is false. You can write ActionScript to control these and additional options for the DataGrid component using its properties, methods, and events. For more information, see “DataGrid class (Flash Professional only)” on page 254.
250
Chapter 6: Components Dictionary
Creating an application with the DataGrid component To create an application with the DataGrid component, you must first determine where your data is coming from. The data for a grid can come from a recordset that is fed from a database query in Macromedia ColdFusion, Java, or .Net using Flash Remoting. Data can also come from a data set or an array. To pull the data into a grid, you set the DataGrid.dataProvider property to the recordset, data set, or array. You can also use the methods of the DataGrid and DataGridColumn classes to create data locally. Any Array object in the same frame as a DataGrid component copies the methods, properties, and events of the DataProvider API. To use Flash Remoting to add a DataGrid component to an application:
1. In Flash, select File > New and select Flash Document. 2. In the Components panel, double-click the DataGrid component to add it to the Stage. 3. In the Property inspector, enter the instance name myDataGrid. 4. In the Actions panel on Frame 1, enter the following code: myDataGrid.dataProvider = recordSetInstance;
The Flash Remoting recordset recordSetInstance is assigned to the dataProvider property of myDataGrid. 5. Select Control > Test Movie. To use a local data provider to add a DataGrid component to an application:
1. In Flash, select File > New and select Flash Document. 2. In the Components panel, double-click the DataGrid component to add it to the Stage. 3. In the Property inspector, enter the instance name myDataGrid. 4. In the Actions panel on Frame 1, enter the following code: myDP = new Array({name:"Chris", price:"Priceless"}, {name:"Nigel", price:"Cheap"}); myDataGrid.dataProvider = myDP;
The name and price fields are used as the column headings, and their values fill the cells in each row. 5. Select Control > Test Movie.
Customizing the DataGrid component (Flash Professional only) You can transform a DataGrid component horizontally and vertically during authoring and runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()). If there is no horizontal scroll bar, column widths adjust proportionally. If column (and therefore, cell) size adjustment occurs, text in the cells may be clipped.
DataGrid component (Flash Professional only)
251
Using styles with the DataGrid component You can set style properties to change the appearance of a DataGrid component. The DataGrid component inherits styles from the List component. (See “Using styles with the List component” on page 453.) The DataGrid component also supports the following styles: Style
Theme Description
backgroundColor
Both
The background color, which can be set for the whole grid or for each column.
backgroundDisabledColor
Both
The background color when the component’s enabled property is set to "false". The default value is 0xDDDDDD (medium gray).
border styles
Both
The DataGrid component uses a RectBorder instance as its border and responds to the styles defined on that class. See “RectBorder class” on page 647. The default border style value is "inset".
headerColor
Both
The color of the column headers. The default value is 0xEAEAEA (light gray)
headerStyle
Both
A CSS style declaration for the column header that can be applied to a grid or column to customize the header styles.
color
Both
The text color. The default value is 0x0B333C for the Halo theme and blank for the Sample theme.
disabledColor
Both
The color for text when the component is disabled. The default color is 0x848384 (dark gray).
embedFonts
Both
A Boolean value that indicates whether the font specified in fontFamily is an embedded font. This style must be set to true if fontFamily refers to an embedded font. Otherwise, the embedded font will not be used. If this style is set to true and fontFamily does not refer to an embedded font, no text will be displayed. The default value is false.
252
fontFamily
Both
The font name for text. The default value is "_sans".
fontSize
Both
The point size for the font. The default value is 10.
fontStyle
Both
The font style: either "normal" or "italic". The default value is "normal".
fontWeight
Both
The font weight: either "none" or "bold". The default value is "none". All components can also accept the value "normal" in place of "none" during a setStyle() call, but subsequent calls to getStyle() will return "none".
textAlign
Both
The text alignment: either "left", "right", or "center". The default value is "left".
textDecoration
Both
The text decoration: either "none" or "underline". The default value is "none".
vGridLines
Both
A Boolean value that indicates whether to show vertical grid lines (true) or not (false). The default value is true.
Chapter 6: Components Dictionary
Style
Theme Description
hGridLines
Both
A Boolean value that indicates whether to show horizontal grid lines (true) or not (false). The default value is false.
vGridLineColor
Both
The color of the vertical grid lines. The default value is 0x666666 (medium gray).
hGridLineColor
Both
The color of the horizontal grid lines. The default value is 0x666666 (medium gray).
Setting styles for an individual column
Color and text styles can be set for the grid as a whole or for a column. You can use the following syntax to set a style for a particular column: grid.getColumnAt(3).setStyle("backgroundColor", 0xFF00AA);
Setting header styles
You can set header styles through headerStyle, which is a style property itself. To do this, you create an instance of CSSStyleDeclaration, set the appropriate properties on that instance for the header, and then assign the CSSStyleDeclaration to the headerStyle property, as shown in the following example. import mx.styles.CSSStyleDeclaration; var headerStyles = new CSSStyleDeclaration(); headerStyles.setStyle("fontStyle", "italic"); grid.setStyle("headerStyle", headerStyles);
Setting styles for all DataGrid components in a document
The DataGrid class inherits from the List class, which inherits from the ScrollSelectList class. The default class-level style properties are defined on the ScrollSelectList class, which the Menu component and all List-based components extend. You can set new default style values on this class directly, and these new settings will be reflected in all affected components. _global.styles.ScrollSelectList.setStyle("backgroundColor", 0xFF00AA);
To set a style property on the DataGrid components only, you can create a new instance of CSSStyleDeclaration and store it in _global.styles.DataGrid. import mx.styles.CSSStyleDeclaration; if (_global.styles.DataGrid == undefined) { _global.styles.DataGrid = new CSSStyleDeclaration(); } _global.styles.DataGrid.setStyle("backgroundColor", 0xFF00AA);
When creating a new class-level style declaration, you will lose all default values provided by the ScrollSelectList declaration, including backgroundColor, which is required for supporting mouse events. To create a class-level style declaration and preserve defaults, use a for..in loop to copy the old settings to the new declaration. var source = _global.styles.ScrollSelectList; var target = _global.styles.DataGrid; for (var style in source) {
DataGrid component (Flash Professional only)
253
target.setStyle(style, source.getStyle(style)); }
For more information about class-level styles, see “Setting styles for a component class” on page 71. Using skins with the DataGrid component The skins that the DataGrid component uses to represent its visual states are included in the subcomponents that constitute the data grid (scroll bars and RectBorder). For information about their skins, see “Using skins with the UIScrollBar component” on page 831 and “RectBorder class” on page 647. DataGrid class (Flash Professional only) Inheritance
MovieClip > UIObject class > UIComponent class > View > ScrollView > ScrollSelectList > List component > DataGrid
ActionScript Class Name
mx.controls.DataGrid
Each component class has a version property, which is a class property. Class properties are available only on the class itself. The version property returns a string that indicates the version of the component. To access this property, use the following code: trace(mx.controls.DataGrid.version); Note: The code trace(myDataGridInstance.version); returns undefined.
Method summary for the DataGrid class The following table lists methods of the DataGrid class. Method
Description
DataGrid.addColumn()
Adds a column to the data grid.
DataGrid.addColumnAt()
Adds a column to the data grid at a specified location.
DataGrid.addItem()
Adds an item to the data grid.
DataGrid.addItemAt()
Adds an item to the data grid at a specified location.
DataGrid.editField()
Replaces the cell data at a specified location.
DataGrid.getColumnAt()
Gets a reference to a column at a specified location.
DataGrid.getColumnIndex()
Gets a reference to the DataGridColumn object at the specified index.
DataGrid.removeAllColumns()
Removes all columns from a data grid.
DataGrid.removeColumnAt()
Removes a column from a data grid at a specified location.
DataGrid.replaceItemAt()
Replaces an item at a specified location with another item.
DataGrid.spaceColumnsEqually() Spaces all columns equally.
254
Chapter 6: Components Dictionary
Methods inherited from the UIObject class
The following table lists the methods the DataGrid class inherits from the UIObject class. When calling these methods, use the form dataGridInstance.methodName. Method
Description
UIObject.createClassObject()
Creates an object on the specified class.
UIObject.createObject()
Creates a subobject on an object.
UIObject.destroyObject()
Destroys a component instance.
UIObject.doLater()
Calls a function when parameters have been set in the Property and Component inspectors.
UIObject.getStyle()
Gets the style property from the style declaration or object.
UIObject.invalidate()
Marks the object so it will be redrawn on the next frame interval.
UIObject.move()
Moves the object to the requested position.
UIObject.redraw()
Forces validation of the object so it is drawn in the current frame.
UIObject.setSize()
Resizes the object to the requested size.
UIObject.setSkin()
Sets a skin in the object.
UIObject.setStyle()
Sets the style property on the style declaration or object.
Methods inherited from the UIComponent class
The following table lists the methods the DataGrid class inherits from the UIComponent class. When calling these methods, use the form dataGridInstance.methodName. Method
Description
UIComponent.getFocus()
Returns a reference to the object that has focus.
UIComponent.setFocus()
Sets focus to the component instance.
Methods inherited from the List class
The following table lists the methods the DataGrid class inherits from the List class. When calling these methods, use the form dataGridInstance.methodName. Method
Description
List.addItem()
Adds an item to the end of the list.
List.addItemAt()
Adds an item to the list at the specified index.
List.getItemAt()
Returns the item at the specified index.
List.removeAll()
Removes all items from the list.
List.removeItemAt()
Removes the item at the specified index.
List.replaceItemAt()
Replaces the item at the specified index with another item.
List.setPropertiesAt()
Applies the specified properties to the specified item.
DataGrid component (Flash Professional only)
255
Method
Description
List.sortItems()
Sorts the items in the list according to the specified compare function.
List.sortItemsBy()
Sorts the items in the list according to a specified property.
Property summary for the DataGrid class The following table lists the properties of the DataGrid class. Property
Description
DataGrid.columnCount
Read-only; the number of columns that are displayed.
DataGrid.columnNames
An array of field names within each item that are displayed as columns.
DataGrid.dataProvider
The data model for a data grid.
DataGrid.editable
A Boolean value that indicates whether the data grid is editable (true) or not (false).
DataGrid.focusedCell
Defines the cell that has focus.
DataGrid.headerHeight
The height of the column headers, in pixels.
DataGrid.hScrollPolicy
Indicates whether a horizontal scroll bar is present ("on"), not present ("off"), or appears when necessary ("auto").
DataGrid.resizableColumns
A Boolean value that indicates whether the columns are resizable (true) or not (false).
DataGrid.selectable
A Boolean value that indicates whether the data grid is selectable (true) or not (false).
DataGrid.showHeaders
A Boolean value that indicates whether the column headers are visible (true) or not (false).
DataGrid.sortableColumns
A Boolean value that indicates whether the columns are sortable (true) or not (false).
Properties inherited from the UIObject class
The following table lists the properties the DataGrid class inherits from the UIObject class. When accessing these properties from the DataGrid object, use the form dataGridInstance.propertyName.
256
Property
Description
UIObject.bottom
The position of the bottom edge of the object, relative to the bottom edge of its parent. Read-only.
UIObject.height
The height of the object, in pixels. Read-only.
UIObject.left
The left edge of the object, in pixels. Read-only.
UIObject.right
The position of the right edge of the object, relative to the right edge of its parent. Read-only.
Chapter 6: Components Dictionary
Property
Description
UIObject.scaleX
A number indicating the scaling factor in the x direction of the object, relative to its parent.
UIObject.scaleY
A number indicating the scaling factor in the y direction of the object, relative to its parent.
UIObject.top
The position of the top edge of the object, relative to its parent. Read-only.
UIObject.visible
A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width
The width of the object, in pixels. Read-only.
UIObject.x
The left edge of the object, in pixels. Read-only.
UIObject.y
The top edge of the object, in pixels. Read-only.
Properties inherited from the UIComponent class
The following table lists the properties the DataGrid class inherits from the UIComponent class. When accessing these properties from the DataGrid object, use the form dataGridInstance.propertyName. Property
Description
UIComponent.enabled
Indicates whether the component can receive focus and input.
UIComponent.tabIndex
A number indicating the tab order for a component in a document.
Properties inherited from the List class
The following table lists the properties the DataGrid class inherits from the List class. When accessing these properties from the DataGrid object, use the form dataGridInstance.propertyName. Property
Description
List.cellRenderer
Assigns the class or symbol to use to display each row of the list.
List.dataProvider
The source of the list items.
List.hPosition
The horizontal position of the list.
List.hScrollPolicy
Indicates whether the horizontal scroll bar is displayed ("on") or not ("off").
List.iconField
A field in each item to be used to specify icons.
List.iconFunction
A function that determines which icon to use.
List.labelField
Specifies a field of each item to be used as label text.
List.labelFunction
A function that determines which fields of each item to use for the label text.
List.length
The number of items in the list. This property is read-only.
DataGrid component (Flash Professional only)
257
Property
Description
List.maxHPosition
The number of pixels the list can scroll to the right, when List.hScrollPolicy is set to "on".
List.multipleSelection
Indicates whether multiple selection is allowed in the list (true) or not (false).
List.rowCount
The number of rows that are at least partially visible in the list.
List.rowHeight
The pixel height of every row in the list.
List.selectable
Indicates whether the list is selectable (true) or not (false).
List.selectedIndex
The index of a selection in a single-selection list.
List.selectedIndices
An array of the selected items in a multiple-selection list.
List.selectedItem
The selected item in a single-selection list. This property is readonly.
List.selectedItems
The selected item objects in a multiple-selection list. This property is read-only.
List.vPosition
Scrolls the list so the topmost visible item is the number assigned.
List.vScrollPolicy
Indicates whether the vertical scroll bar is displayed ("on"), not displayed ("off"), or displayed when needed ("auto").
Event summary for the DataGrid class The following table lists the events of the DataGrid class. Event
Description
DataGrid.cellEdit
Broadcast when the cell value has changed.
DataGrid.cellFocusIn
Broadcast when a cell receives focus.
DataGrid.cellFocusOut
Broadcast when a cell loses focus.
DataGrid.cellPress
Broadcast when a cell is pressed (clicked).
DataGrid.change
Broadcast when an item has been selected.
DataGrid.columnStretch
Broadcast when a user resizes a column horizontally.
DataGrid.headerRelease
Broadcast when a user clicks (releases) a header.
Events inherited from the UIObject class
The following table lists the events the DataGrid class inherits from the UIObject class.
258
Event
Description
UIObject.draw
Broadcast when an object is about to draw its graphics.
UIObject.hide
Broadcast when an object’s state changes from visible to invisible.
UIObject.load
Broadcast when subobjects are being created.
Chapter 6: Components Dictionary
Event
Description
UIObject.move
Broadcast when the object has moved.
UIObject.resize
Broadcast when an object has been resized.
UIObject.reveal
Broadcast when an object’s state changes from invisible to visible.
UIObject.unload
Broadcast when the subobjects are being unloaded.
Events inherited from the UIComponent class
The following table lists the events the DataGrid class inherits from the UIComponent class. Event
Description
UIComponent.focusIn
Broadcast when an object receives focus.
UIComponent.focusOut
Broadcast when an object loses focus.
UIComponent.keyDown
Broadcast when a key is pressed.
UIComponent.keyUp
Broadcast when a key is released.
Events inherited from the List class
The following table lists the events the DataGrid class inherits from the List class. Event
Description
List.change
Broadcast whenever user interaction causes the selection to change.
List.itemRollOut
Broadcast when the pointer rolls over and then off of list items.
List.itemRollOver
Broadcast when the pointer rolls over list items.
List.scroll
Broadcast when a list is scrolled.
DataGrid.addColumn() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.addColumn(dataGridColumn) myDataGrid.addColumn(name) Parameters dataGridColumn name
An instance of the DataGridColumn class.
A string that indicates the name of a new DataGridColumn object to be inserted.
DataGrid component (Flash Professional only)
259
Returns
A reference to the DataGridColumn object that was added. Description
Method; adds a new column to the end of the data grid. For more information, see “DataGridColumn class (Flash Professional only)” on page 278. Example
The following code adds a new DataGridColumn object named Purple: import mx.controls.gridclasses.DataGridColumn; myGrid.addColumn(new DataGridColumn("Purple"));
DataGrid.addColumnAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.addColumnAt(index, name) myDataGrid.addColumnAt(index, dataGridColumn) Parameters
The index position at which the DataGridColumn object is added. The first position is 0.
index
name
A string that indicates the name of the DataGridColumn object.
dataGridColumn
An instance of the DataGridColumn class.
Returns
A reference to the DataGridColumn object that was added. Description
Method; adds a new column at the specified position. Columns are shifted to the right and their indexes are incremented. For more information, see “DataGridColumn class (Flash Professional only)” on page 278. Example
The following example inserts a new DataGridColumn object called "Green" at the second and fourth columns: import mx.controls.gridclasses.DataGridColumn; myGrid.addColumnAt(1, "Green"); myGrid.addColumnAt(3, new DataGridColumn("Purple"));
260
Chapter 6: Components Dictionary
DataGrid.addItem() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.addItem(item) Parameters item
An instance of an object to be added to the grid.
Returns
A reference to the instance that was added. Description
Method; adds an item to the end of the grid (after the last item index). Note: This differs from the List.addItem() method in that an object is passed rather than a string. Example
The following example adds a new object to the grid myGrid: var anObject= {name:"Jim!!", age:30}; myGrid.addItem(anObject);
DataGrid.addItemAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.addItemAt(index, item) Parameters
The index position (among the child nodes) at which the node should be added. The first position is 0.
index
item
A string that displays the node.
Returns
A reference to the object instance that was added. Description
Method; adds an item to the grid at the position specified.
DataGrid component (Flash Professional only)
261
Example
The following example inserts an object instance to the grid at index position 4: var anObject= {name:"Jim!!", age:30}; myGrid.addItemAt(4, anObject);
DataGrid.cellEdit Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage listenerObject = new Object(); listenerObject.cellEdit = function(eventObject){ // insert your code here } myDataGridInstance.addEventListener("cellEdit", listenerObject) Description
Event; broadcast to all registered listeners when cell value changes. Version 2 components use a dispatcher/listener event model. The DataGrid component dispatches a cellEdit event when the value of a cell has changed, and the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter. When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.cellEdit event’s event object has four additional properties: columnIndex itemIndex oldValue type
A number that indicates the index of the target column. A number that indicates the index of the target row.
The previous value of the cell.
The string "cellEdit".
For more information, see “EventDispatcher class” on page 415. Example
In the following example, a handler called myDataGridListener is defined and passed to myDataGrid.addEventListener() as the second parameter. The event object is captured by the cellEdit handler in the eventObject parameter. When the cellEdit event is broadcast, a trace statement is sent to the Output panel. myDataGridListener = new Object(); myDataGridListener.cellEdit = function(event){
262
Chapter 6: Components Dictionary
var cell = "(" + event.columnIndex + ", " + event.itemIndex + ")"; trace("The value of the cell at " + cell + " has changed"); } myDataGrid.addEventListener("cellEdit", myDataGridListener); Note: The grid must be editable for the above code to work.
DataGrid.cellFocusIn Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage listenerObject = new Object(); listenerObject.cellFocusIn = function(eventObject){ // insert your code here } myDataGridInstance.addEventListener("cellFocusIn", listenerObject) Description
Event; broadcast to all registered listeners when a particular cell receives focus. This event is broadcast after any previously edited cell’s editCell and cellFocusOut events are broadcast. Version 2 components use a dispatcher/listener event model. When a DataGrid component dispatches a cellFocusIn event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter. When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.cellFocusIn event’s event object has three additional properties: columnIndex itemIndex type
A number that indicates the index of the target column. A number that indicates the index of the target row.
The string "cellFocusIn".
For more information, see “EventDispatcher class” on page 415. Example
In the following example, a handler called myListener is defined and passed to grid.addEventListener() as the second parameter. The event object is captured by the cellFocusIn handler in the eventObject parameter. When the cellFocusIn event is broadcast, a trace statement is sent to the Output panel. var myListener = new Object(); myListener.cellFocusIn = function(event) { var cell = "(" + event.columnIndex + ", " + event.itemIndex + ")";
DataGrid component (Flash Professional only)
263
trace("The cell at " + cell + " has gained focus"); }; grid.addEventListener("cellFocusIn", myListener); Note: The grid must be editable for the above code to work.
DataGrid.cellFocusOut Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage listenerObject = new Object(); listenerObject.cellFocusOut = function(eventObject){ // insert your code here } myDataGridInstance.addEventListener("cellFocusOut", listenerObject) Description
Event; broadcast to all registered listeners whenever a user moves off a cell that has focus. You can use the event object properties to isolate the cell that was left. This event is broadcast after the cellEdit event and before any subsequent cellFocusIn events are broadcast by the next cell. Version 2 components use a dispatcher/listener event model. When a DataGrid component dispatches a cellFocusOut event, the event is handled by a function (also called a handler) that is attached to a listener object that you create. You call the addEventListener() method and pass it the name of the handler as a parameter. When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.cellFocusOut event’s event object has three additional properties: columnIndex itemIndex type
A number that indicates the index of the target column. The first position is 0. A number that indicates the index of the target row. The first position is 0.
The string "cellFocusOut".
For more information, see “EventDispatcher class” on page 415. Example
In the following example, a handler called myListener is defined and passed to grid.addEventListener() as the second parameter. The event object is captured by the cellFocusOut handler in the eventObject parameter. When the cellFocusOut event is broadcast, a trace statement is sent to the Output panel. var myListener = new Object(); myListener.cellFocusOut = function(event) { var cell = "(" + event.columnIndex + ", " + event.itemIndex + ")";
264
Chapter 6: Components Dictionary
trace("The cell at " + cell + " has lost focus"); }; grid.addEventListener("cellFocusOut", myListener); Note: The grid must be editable for the above code to work.
DataGrid.cellPress Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage listenerObject = new Object(); listenerObject.cellPress = function(eventObject){ // insert your code here } myDataGridInstance.addEventListener("cellPress", listenerObject) Description
Event; broadcast to all registered listeners when a user presses the mouse button on a cell. Version 2 components use a dispatcher/listener event model. When a DataGrid component broadcasts a cellPress event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter. When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.cellPress event’s event object has three additional properties: columnIndex
A number that indicates the index of the column that was pressed. The first
position is 0. itemIndex
A number that indicates the index of the row that was pressed. The first position is
0. type
The string "cellPress".
For more information, see “EventDispatcher class” on page 415. Example
In the following example, a handler called myListener is defined and passed to grid.addEventListener() as the second parameter. The event object is captured by the cellPress handler in the eventObject parameter. When the cellPress event is broadcast, a trace statement is sent to the Output panel. var myListener = new Object(); myListener.cellPress = function(event) { var cell = "(" + event.columnIndex + ", " + event.itemIndex + ")";
DataGrid component (Flash Professional only)
265
trace("The cell at " + cell + " has been clicked"); }; grid.addEventListener("cellPress", myListener);
DataGrid.change Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage listenerObject = new Object(); listenerObject.change = function(eventObject){ // insert your code here } myDataGridInstance.addEventListener("change", listenerObject) Description
Event; broadcast to all registered listeners when an item has been selected. Version 2 components use a dispatcher/listener event model. When a DataGrid component dispatches a change event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter. When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.change event’s event object has one additional property, type, whose value is "change". For more information, see “EventDispatcher class” on page 415. Example
In the following example, a handler called myListener is defined and passed to grid.addEventListener() as the second parameter. The event object is captured by change handler in the eventObject parameter. When the change event is broadcast, a trace statement is sent to the Output panel. var myListener = new Object(); myListener.change = function(event) { trace("The selection has changed to " + event.target.selectedIndex); }; grid.addEventListener("change", myListener);
266
Chapter 6: Components Dictionary
DataGrid.columnCount Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.columnCount Description
Property (read-only); the number of columns displayed. Example
The following example gets the number of displayed columns in the DataGrid instance grid: var c = grid.columnCount;
DataGrid.columnNames Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.columnNames Description
Property; an array of field names within each item that are displayed as columns. Example
The following example tells the grid instance to display only these three fields as columns: grid.columnNames = ["Name", "Description", "Price"];
DataGrid.columnStretch Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004.
DataGrid component (Flash Professional only)
267
Usage listenerObject = new Object(); listenerObject.columnStretch = function(eventObject){ // insert your code here } myDataGridInstance.addEventListener("columnStretch", listenerObject) Description
Event; broadcast to all registered listeners when a user resizes a column horizontally. Version 2 components use a dispatcher/listener event model. When a DataGrid component dispatches a columnStretch event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter. When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.columnStretch event’s event object has two additional properties: columnIndex type
A number that indicates the index of the target column. The first position is 0.
The string "columnStretch".
For more information, see “EventDispatcher class” on page 415. Example
In the following example, a handler called myListener is defined and passed to grid.addEventListener() as the second parameter. The event object is captured by the columnStretch handler in the eventObject parameter. When the columnStretch event is broadcast, a trace statement is sent to the Output panel. var myListener = new Object(); myListener.columnStretch = function(event) { trace("column " + event.columnIndex + " was resized"); }; grid.addEventListener("columnStretch", myListener);
DataGrid.dataProvider Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.dataProvider Description
Property; the data model for items viewed in a DataGrid component.
268
Chapter 6: Components Dictionary
The data grid adds methods to the prototype of the Array class so that each Array object conforms to the DataProvider API (see DataProvider.as in the Classes/mx/controls/listclasses folder). Any array that is in the same frame or screen as a data grid automatically has all the methods (addItem(), getItemAt(), and so on) needed for it to be the data model of a data grid, and can be used to broadcast data model changes to multiple components. In a DataGrid component, you specify fields for display in the DataGrid.columnNames property. If you don’t define the column set (by setting the DataGrid.columnNames property or by calling DataGrid.addColumn()) for the data grid before the DataGrid.dataProvider property has been set, the data grid generates columns for each field in the data provider’s first item, once that item arrives. Any object that implements the DataProvider API can be used as a data provider for a data grid (including Flash Remoting recordsets, data sets, and arrays). Use a grid’s data provider to communicate with the data in the grid because the data provider remains consistent, regardless of scroll position. Example
The following example creates an array to be used as a data provider and assigns it directly to the dataProvider property: grid.dataProvider = [{name:"Chris", price:"Priceless"}, {name:"Nigel", price:"cheap"}];
The following example creates a new Array object that is decorated with the DataProvider API. It uses a for loop to add 20 items to the grid: myDP = new Array(); for (var i=0; i<20; i++) myDP.addItem({name:"Nivesh", price:"Priceless"}); list.dataProvider = myDP
DataGrid.editable Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.editable Description
Property; determines whether the data grid can be edited by a user (true) or not (false). This property must be true in order for individual columns to be editable and for any cell to receive focus. The default value is false. If you want individual columns to be uneditable, use the DataGridColumn.editable property.
DataGrid component (Flash Professional only)
269
Caution: The DataGrid is not editable or sortable if it is bound directly to a WebServiceConnector component or an XMLConnector component. You must bind the DataGrid component to the DataSet component and bind the DataSet component to the WebServiceConnector component or XMLConnector component if you want the grid to be editable or sortable. For more information, see Chapter 14, “Data Integration (Flash Professional Only),” in Using Flash. Example
The following example allows users to edit all the columns of the grid except the first column: myDataGrid.editable = true; myDataGrid.getColumnAt(0).editable = false; See also DataGridColumn.editable
DataGrid.editField() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.editField(index, colName, data) Parameters
The index of the target cell. This number is zero-based.
index colName data
A string indicating the name of the column (field) that contains the target cell.
The value to be stored in the target cell. This parameter can be of any data type.
Returns
The data that was in the cell. Description
Method; replaces the cell data at the specified location and refreshes the data grid with the new value. Any cell present for that value will have its setValue() method triggered. Example
The following example places a value in the grid: var prevValue = myGrid.editField(5, "Name", "Neo");
270
Chapter 6: Components Dictionary
DataGrid.focusedCell Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.focusedCell Description
Property; in editable mode only, an object instance that defines the cell that has focus. The object must have the fields columnIndex and itemIndex, which are both integers that indicate the index of the column and item of the cell. The origin is (0,0). The default value is undefined. Example
The following example sets the focused cell to the third column, fourth row: grid.focusedCell = {columnIndex:2, itemIndex:3};
DataGrid.getColumnAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index) Parameters index
The index of the DataGridColumn object to be returned. This number is zero-based.
Returns
A DataGridColumn object. Description
Method; gets a reference to the DataGridColumn object at the specified index. Example
The following example gets the DataGridColumn object at index 4: var aColumn = myGrid.getColumnAt(4);
DataGrid component (Flash Professional only)
271
DataGrid.getColumnIndex() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnIndex(columnName) Parameters columnName
A string that is the name of a column.
Returns
A number that specifies the index of the column. Description
Method; returns the index of the column specified by the columnName parameter. DataGrid.headerHeight Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.headerHeight Description
Property; the height of the header bar of the data grid, in pixels. The default value is 20. Example
The following example sets the scroll position to the top of the display: myDataGrid.headerHeight = 30;
DataGrid.headerRelease Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004.
272
Chapter 6: Components Dictionary
Usage listenerObject = new Object(); listenerObject.headerRelease = function(eventObject){ // insert your code here } myDataGridInstance.addEventListener("headerRelease", listenerObject) Description
Event; broadcast to all registered listeners when a column header has been released. You can use this event with the DataGridColumn.sortOnHeaderRelease property to prevent automatic sorting and to let you sort as you like. Version 2 components use a dispatcher/listener event model. When the DataGrid component dispatches a headerRelease event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter. When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.headerRelease event’s event object has two additional properties: columnIndex type
A number that indicates the index of the target column.
The string "headerRelease".
For more information, see “EventDispatcher class” on page 415. Example
In the following example, a handler called myListener is defined and passed to grid.addEventListener() as the second parameter. The event object is captured by the headerRelease handler in the eventObject parameter. When the headerRelease event is broadcast, a trace statement is sent to the Output panel. var myListener = new Object(); myListener.headerRelease = function(event) { trace("column " + event.columnIndex + " header was pressed"); }; grid.addEventListener("headerRelease", myListener);
DataGrid.hScrollPolicy Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.hScrollPolicy
DataGrid component (Flash Professional only)
273
Description
Property; specifies whether the data grid has a horizontal scroll bar. This property can have the value "on", "off", or "auto". The default value is "off". If hScrollPolicy is set to "off", columns scale proportionally to accommodate the finite width. Note: This differs from the List component, which cannot have hScrollPolicy set to "auto". Example
The following example sets horizontal scroll policy to automatic, which means that the horizontal scroll bar appears if it’s necessary to display all the content: myDataGrid.hScrollPolicy = "auto";
DataGrid.removeAllColumns() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.removeAllColumns() Parameters
None. Returns
Nothing. Description
Method; removes all DataGridColumn objects from the data grid. Calling this method has no effect on the data provider. Call this method if you are setting a new data provider that has different fields from the previous data provider, and you want to clear the fields that are displayed. Example
The following example removes all DataGridColumn objects from myDataGrid: myDataGrid.removeAllColumns();
DataGrid.removeColumnAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004.
274
Chapter 6: Components Dictionary
Usage myDataGrid.removeColumnAt(index) Parameters
The index of the column to remove.
index Returns
A reference to the DataGridColumn object that was removed. Description
Method; removes the DataGridColumn object at the specified index. Example
The following example removes the DataGridColumn object at index 2 in myDataGrid: myDataGrid.removeColumnAt(2);
DataGrid.replaceItemAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.replaceItemAt(index, item) Parameters index item
The index of the item to be replaced. An object that is the item value to use as a replacement.
Returns
The previous value. Description
Method; replaces the item at a specified index and refreshes the display of the grid. Example
The following example replaces the item at index 4 with the item defined in aNewValue: var aNewValue = {name:"Jim", value:"tired"}; var prevValue = myGrid.replaceItemAt(4, aNewValue);
DataGrid component (Flash Professional only)
275
DataGrid.resizableColumns Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.resizableColumns Description
Property; a Boolean value that determines whether the columns of the grid can be stretched by the user (true) or not (false). This property must be true for individual columns to be resizable by the user. The default value is true. Example
The following example prevents users from resizing columns: myDataGrid.resizableColumns = false;
DataGrid.selectable Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.selectable Description
Property; a Boolean value that determines whether a user can select the data grid (true) or not (false). The default value is true. Example
The following example prevents the grid from being selected: myDataGrid.selectable = false;
DataGrid.showHeaders Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004.
276
Chapter 6: Components Dictionary
Usage myDataGrid.showHeaders Description
Property; a Boolean value that indicates whether the data grid displays the column headers (true) or not (false). Column headers are shaded to differentiate them from the other rows in a grid. Users can click column headers to sort the contents of the column if DataGrid.sortableColumns is set to true. The default value of showHeaders is true. Example
The following example hides the column headers: myDataGrid.showHeaders = false; See also DataGrid.sortableColumns
DataGrid.sortableColumns Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.sortableColumns Description
Property; a Boolean value that determines whether the columns of the data grid can be sorted (true) or not (false) when a user clicks the column headers. This property must be true for individual columns to be sortable, and for the headerRelease event to be broadcast. The default value is true. Caution: The DataGrid is not editable or sortable if it is bound directly to a WebServiceConnector component or an XMLConnector component. You must bind the DataGrid component to the DataSet component and bind the DataSet component to the WebServiceConnector component or XMLConnector component if you want the grid to be editable or sortable. For more information, see Chapter 14, “Data Integration (Flash Professional Only),” in Using Flash. Example
The following example turns off sorting: myDataGrid.sortableColumns = false; See also DataGrid.headerRelease
DataGrid component (Flash Professional only)
277
DataGrid.spaceColumnsEqually() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.spaceColumnsEqually() Parameters
None. Returns
Nothing. Description
Method; respaces the columns equally. Example
The following example respaces the columns of myGrid when any column header is pressed and released: myGrid.showHeaders = true myGrid.dataProvider = [{guitar:"Flying V", name:"maggot"}, {guitar:"SG", name:"dreschie"}, {guitar:"jagstang", name:"vitapup"}]; gridLO = new Object(); gridLO.headerRelease = function(){ myGrid.spaceColumnsEqually(); } myGrid.addEventListener("headerRelease", gridLO);
DataGridColumn class (Flash Professional only) ActionScript Class Name
mx.controls.gridclasses.DataGridColumn
You can create and configure DataGridColumn objects to use as columns of a data grid. Many of the methods of the DataGrid class are dedicated to managing DataGridColumn objects. DataGridColumn objects are stored in an zero-based array in the data grid; 0 is the leftmost column. After columns have been added or created, you can access them by calling DataGrid.getColumnAt(index). There are three ways to add or create columns in a grid. If you want to configure your columns, it is best to use either the second or third way before you add data to a data grid so you don’t have to create columns twice.
• Adding a data provider or an item with multiple fields to a grid that has no configured DataGridColumn objects automatically generates columns for every field in the reverse order of the for..in loop.
278
Chapter 6: Components Dictionary
•
takes in the field names of the desired item fields and generates DataGridColumn objects, in order, for each field listed. This approach lets you select and order columns quickly with a minimal amount of configuration. This approach removes any previous column information.
DataGrid.columnNames
• The most flexible way to add columns is to prebuild them as DataGridColumn objects and add them to the data grid by using DataGrid.addColumn(). This approach is useful because it lets you add columns with proper sizing and formatting before the columns ever reach the grid (which reduces processor demand). For more information, see “Constructor for the DataGridColumn class” on page 279. Property summary for the DataGridColumn class The following table lists the properties of the DataGridColumn class. Property
Description
DataGridColumn.cellRenderer
The linkage identifier of a symbol to be used to display the cells in this column.
DataGridColumn.columnName
Read-only; the name of the field associated with the column.
DataGridColumn.editable
A Boolean value that indicates whether a column is editable (true) or not (false).
DataGridColumn.headerRenderer
The name of a class to be used to display the header of this column.
DataGridColumn.headerText
The text for the header of this column.
DataGridColumn.labelFunction
A function that determines which field of an item to display.
DataGridColumn.resizable
A Boolean value that indicates whether a column is resizable (true) or not (false).
DataGridColumn.sortable
A Boolean value that indicates whether a column is sortable (true) or not (false).
DataGridColumn.sortOnHeaderRelease A Boolean value that indicates whether a column is sorted (true) or not (false) when a user clicks a column header. DataGridColumn.width
The width of a column, in pixels.
Constructor for the DataGridColumn class Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage new DataGridColumn(name)
DataGrid component (Flash Professional only)
279
Parameters name A string that indicates the name of the DataGridColumn object. This parameter is the field of each item to display. Returns
Nothing. Description
Constructor; creates a DataGridColumn object. Use this constructor to create columns to add to a DataGrid component. After you create the DataGridColumn objects, you can add them to a data grid by calling DataGrid.addColumn(). Example
The following example creates a DataGridColumn object called Location: import mx.controls.gridclasses.DataGridColumn; var column = new DataGridColumn("Location");
DataGridColumn.cellRenderer Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).cellRenderer Description
Property; a linkage identifier for a symbol to be used to display cells in this column. Any class used for this property must implement the CellRenderer API (see “CellRenderer API” on page 145.) The default value is undefined. Example
The following example uses a linkage identifier to set a new cell renderer: myGrid.getColumnAt(3).cellRenderer = "MyCellRenderer";
DataGridColumn.columnName Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).columnName
280
Chapter 6: Components Dictionary
Description
Property (read-only); the name of the field associated with this column. The default value is the name called in the DataGridColumn constructor. Example
The following example assigns the column name of the column at the third index position to the variable name: var name = myGrid.getColumnAt(3).columnName; See also
Constructor for the DataGridColumn class DataGridColumn.editable Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).editable Description
Property; determines whether the column can be edited by a user (true) or not (false). The DataGrid.editable property must be true in order for individual columns to be editable, even when DataGridColumn.editable is set to true. The default value is true. Caution: The DataGrid is not editable or sortable if it is bound directly to a WebServiceConnector component or an XMLConnector component. You must bind the DataGrid component to the DataSet component and bind the DataSet component to the WebServiceConnector component or XMLConnector component if you want the grid to be editable or sortable. For more information, see Chapter 14, “Data Integration (Flash Professional Only),” in Using Flash. Example
The following example prevents the first column in a grid from being edited: myDataGrid.getColumnAt(0).editable = false; See also DataGrid.editable
DataGrid component (Flash Professional only)
281
DataGridColumn.headerRenderer Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).headerRenderer Description
Property; a string that indicates a class name to be used to display the header of this column. Any class used for this property must implement the CellRenderer API (see “CellRenderer API” on page 145). The default value is undefined. Example
The following example uses a linkage identifier to set a new header renderer: myGrid.getColumnAt(3).headerRenderer = "MyHeaderRenderer";
DataGridColumn.headerText Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).headerText Description
Property; the text in the column header. The default value is the column name. This property allows you to display something other than the field name as the header. Example
The following example sets the column header text to “The Price”: var myColumn = new DataGridColumn("price"); myColumn.headerText = "The Price";
Property; specifies a function to determine which field (or field combination) of each item to display. This function receives one parameter, item, which is the item being rendered, and must return a string representing the text to display. This property can be used to create virtual columns that have no equivalent field in the item. Note: The specified function operates in a nondefined scope. Example
The following example creates a virtual column: var myCol = myGrid.addColumn("Subtotal"); myCol.labelFunction = function(item) { return "$" + (item.price + (item.price * salesTax)); };
DataGridColumn.resizable Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).resizable Description
Property; a Boolean value that indicates whether a column can be resized by a user (true) or not (false). The DataGrid.resizableColumns property must be set to true for this property to take effect. The default value is true. Example
The following example prevents the column at index 1 from being resized: myGrid.getColumnAt(1).resizable = false;
DataGridColumn.sortable Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).sortable
DataGrid component (Flash Professional only)
283
Description
Property; a Boolean value that indicates whether a column can be sorted by a user (true) or not (false). The DataGrid.sortableColumns property must be set to true for this property to take effect. The default value is true. Caution: The DataGrid is not editable or sortable if it is bound directly to a WebServiceConnector component or an XMLConnector component. You must bind the DataGrid component to the DataSet component and bind the DataSet component to the WebServiceConnector component or XMLConnector component if you want the grid to be editable or sortable. For more information, see Chapter 14, “Data Integration (Flash Professional Only),” in Using Flash. Example
The following example prevents the column at index 1 from being sorted: myGrid.getColumnAt(1).sortable = false;
DataGridColumn.sortOnHeaderRelease Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).sortOnHeaderRelease Description
Property; a Boolean value that indicates whether the column is sorted automatically (true) or not (false) when a user clicks a header. This property can be set to true only if DataGridColumn.sortable is set to true. If DataGridColumn.sortOnHeaderRelease is set to false, you can catch the headerRelease event and perform your own sort. The default value is true. Caution: The DataGrid is not editable or sortable if it is bound directly to a WebServiceConnector component or an XMLConnector component. You must bind the DataGrid component to the DataSet component and bind the DataSet component to the WebServiceConnector component or XMLConnector component if you want the grid to be editable or sortable. For more information, see Chapter 14, “Data Integration (Flash Professional Only),” in Using Flash. Example
The following example lets you catch the headerRelease event to perform your own sort: myGrid.getColumnAt(7).sortOnHeaderRelease = false;
284
Chapter 6: Components Dictionary
DataGridColumn.width Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDataGrid.getColumnAt(index).width Description
Property; a number that indicates the width of the column, in pixels. The default value is 50. Example
The following example makes a column half the default width: myGrid.getColumnAt(4).width = 25;
DataGrid component (Flash Professional only)
285
CHAPTER 6 Components Dictionary
DataHolder component (Flash Professional only)
The DataHolder component is a repository for data and a means of generating events when that data has changed. Its main purpose is to hold data and act as a connector between other components that use data binding. Initially, the DataHolder component has a single bindable property named data. You can add more properties by using the Schema tab in the Component inspector. For more information on using the Schema tab, see “Working with schemas in the Schema tab (Flash Professional only)” in Using Flash. You can assign any type of data to a DataHolder property, either by creating a binding between the data and another property, or by using your own ActionScript code. Whenever the value of that data changes, the DataHolder component emits an event whose name is the same as the property, and any bindings associated with that property are executed. In most cases, you will not use this component to build an application. It is needed only when you cannot bind external data directly to another component and you do not want to use a DataSet component. The DataHolder component is useful when you can’t directly bind components (such as connectors, user interface components, or DataSet components) together. Below are some scenarios in which you might use a DataHolder component:
• If a data value is generated by ActionScript, you might want to bind it to some other components. In this case, you could have a DataHolder component that contains properties that are bound as desired. Whenever new values are assigned to those properties (by means of ActionScript, for example) those values will be distributed to the data-bound object.
• You might have a data value that results from a complex indexed data binding, as shown in the following diagram. Web Service Method getMovies
Results
Results[movieList.selectedIndex]
DataModel myDataModel
UI ListBox movieList
data.movieTitle
UI TextField title
data.movieRating
UI TextField rating
data.movieTimes
UI ListBox times
In this case it is convenient to bind the data value to a DataHolder component (called DataModel in this illustration) and then use that for bindings to the user interface.
286
Chapter 6: Components Dictionary
Note: The DataHolder component is not meant to implement the same control over your data as the DataSet component. It does not manage or track data, nor does it have the ability to update data. It is a repository for holding data and generating events when that data has changed.
Creating an application with the DataHolder component (Flash Professional only) In this example, you add an array property to a DataHolder component’s schema (an array) whose value is determined by ActionScript code that you write. You then bind that array property to the dataProvider property of a DataGrid component by using the Bindings tab in the Component inspector. To use the DataHolder component in a simple application:
1. In Flash MX Professional 2004, create a new file. 2. Open the Components panel, drag a DataHolder component to the Stage, and name it
dataHolder. 3. Drag a DataGrid component to the Stage and name it namesGrid. 4. Select the DataHolder component and open the Component inspector. 5. Click the Schema tab in the Component inspector. 6. Click the Add Component Property (+) button located in the top pane of the Schema tab. 7. In the bottom pane of the Schema tab, type namesArray in the Field Name field, and select
Array from the Data Type pop-up menu. 8. Click the Bindings tab in the Component inspector, and add a binding between the
property of the DataHolder component and the dataProvider property of the DataGrid component.
namesArray
For more information on creating bindings with the Bindings tab, see “Working with bindings in the Bindings tab (Flash Professional only)” in Using Flash. 9. In the Timeline, select the first frame on Layer 1 and open the Actions panel. 10. Enter the following code in the Actions panel: dataHolder.namesArray= [{name:"Tim"},{name:"Paul"},{name:"Jason"}];
This code populates the namesArray array with several objects. When this variable assignment executes, the binding that you established previously between the DataHolder component and the DataGrid component executes. 11. Test the file by selecting Control > Test Movie.
DataHolder component (Flash Professional only)
287
DataHolder class Inheritance
MovieClip > DataHolder
ActionScript class name
mx.data.components.DataHolder
The DataHolder component is a repository for data and a means of generating events when that data has changed. Its main purpose is to hold data and act as a connector between other components that use data binding. Initially, the DataHolder component has a single bindable property named data. You can add more properties by using the Schema tab in the Component inspector. Property summary for the DataHolder class The following table lists the properties of the DataHolder class. Property
Description
DataHolder.data
Default bindable property for the DataHolder component.
DataHolder.data Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage dataHolder.data Description
Property; the default item in a DataHolder object’s schema. This property is not a “permanent” member of the DataHolder component. Rather, it is the default bindable property for each instance of the component. You can add your own bindable properties, or delete the default data property, by using the Schema tab in the Component inspector. For more information on using the Schema tab, see “Working with schemas in the Schema tab (Flash Professional only)” in Using Flash. Example
For a step-by-step example of using this component, see “Creating an application with the DataHolder component (Flash Professional only)” on page 287. The following code shows a simple example of how to populate the DataHolder component with data that is a variable. To test the application, you enter a value into the text input field and click the addDate_btn instance, which adds the value to the DataHolder component. Click the dumpDataHolder_btn instance to trace the contents of the DataHolder component.
288
Chapter 6: Components Dictionary
// Drag two Button components onto the Stage (addDate_btn and dumpDataHolder_btn), a TextInput (myDate_txt) and a DataHolder (myDataHolder). Add the following ActionScript to Frame 1: var dhListener:Object = {}; dhListener.click = function() { trace("dumping DataHolder"); trace(" "+myDataHolder.myDate); trace(""); }; var dateListener:Object = {}; dateListener.click = function() { myDataHolder.myDate = myDate_txt.text; trace("added value"); }; this.dumpDataHolder_btn.addEventListener("click", dhListener); this.addDate_btn.addEventListener("click", dateListener);
DataHolder component (Flash Professional only)
289
CHAPTER 6 Components Dictionary
DataProvider API ActionScript Class Name
mx.controls.listclasses.DataProvider
The DataProvider API is a set of methods and properties that a data source needs so that a listbased class can communicate with it. Arrays, recordsets, and data sets implement this API. You can create a DataProvider-compliant class by implementing all the methods and properties described in this section. A list-based component could then use that class as a data provider. The methods of the DataProvider API let you query and modify the data in any component that displays data (also called a view). The DataProvider API also broadcasts change events when the data changes. Multiple views can use the same data provider and receive the change events. A data provider is a linear collection (like an array) of items. Each item is an object composed of many fields of data. You can access these items by index (as you can with an array), using DataProvider.getItemAt(). Data providers are most commonly used with arrays. Data-aware components apply all the methods of the DataProvider API to Array.prototype when an Array object is in the same frame or screen as a data-aware component. This lets you use any existing array as the data for views that have a dataProvider property. Because of the DataProvider API, the version 2 components that provide views for data (DataGrid, List, Tree, and so on) can also display Flash Remoting RecordSet objects and data from the DataSet component. The DataProvider API is the language with which data-aware components communicate with their data providers. In the Macromedia Flash documentation, “DataProvider” is the name of the API, dataProvider is a property of each component that acts as a view for data, and “data provider” is the generic term for a data source. Method summary for the DataProvider API The following table lists the methods of the DataProvider API. Method
Description
DataProvider.addItem()
Adds an item at the end of the data provider.
DataProvider.addItemAt()
Adds an item to the data provider at the specified position.
DataProvider.editField()
Changes one field of the data provider.
DataProvider.getEditingData() Gets the data for editing from a data provider.
290
DataProvider.getItemAt()
Gets a reference to the item at a specified position.
DataProvider.getItemID()
Returns the unique ID of the item.
DataProvider.removeAll()
Removes all items from a data provider.
DataProvider.removeItemAt()
Removes an item from a data provider at a specified position.
DataProvider.replaceItemAt()
Replaces the item at a specified position with another item.
Chapter 6: Components Dictionary
Method
Description
DataProvider.sortItems()
Sorts the items in the data provider according to a compare function or sort options.
DataProvider.sortItemsBy()
Sorts the items in the data provider alphabetically or numerically, in the specified order, using the specified field name.
Property summary for the DataProvider API The following table lists the properties of the DataProvider API. Property
Description
DataProvider.length
The number of items in a data provider.
Event summary for the DataProvider API The following table lists the events of the DataProvider API. Event
Description
DataProvider.modelChanged
Broadcast when the data provider is changed.
DataProvider.addItem() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDP.addItem(item) Parameters item
An object that contains data. This constitutes an item in a data provider.
Returns
Nothing. Description
Method; adds a new item at the end of the data provider. This method triggers the modelChanged event with the event name addItems. Example
The following example adds an item to the end of the data provider myDP: myDP.addItem({label : "this is an Item"});
DataProvider API
291
DataProvider.addItemAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDP.addItemAt(index, item) Parameters
A number greater than or equal to 0. This number indicates the position at which to insert the item; it is the index of the new item.
index
item
An object containing the data for the item.
Returns
Nothing. Description
Method; adds a new item to the data provider at the specified index. Indices greater than the data provider’s length are ignored. This method triggers the modelChanged event with the event name addItems. Example
The following example adds an item to the data provider myDP at the fourth position: myDP.addItemAt(3, {label : "this is the fourth Item"});
DataProvider.editField() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDP.editField(index, fieldName, newData) Parameters index
A number greater than or equal to 0; the index of the item.
fieldName newData
292
A string indicating the name of the field to modify in the item. The new data to put in the data provider.
Chapter 6: Components Dictionary
Returns
Nothing. Description
Method; changes one field of the data provider. This method triggers the modelChanged event with the event name updateField. Example
The following code modifies the label field of the third item: myDP.editField(2, "label", "mynewData");
DataProvider.getEditingData() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDP.getEditingData(index, fieldName) Parameters
A number greater than or equal to 0 and less than DataProvider.length. This number is the index of the item to retrieve.
index
fieldName
A string indicating the name of the field being edited.
Returns
The editable formatted data to be used. Description
Method; retrieves data for editing from a data provider. This lets the data model provide different formats of data for editing and displaying. Example
The following code gets an editable string for the price field: trace(myDP.getEditingData(4, "price");
DataProvider.getItemAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004.
DataProvider API
293
Usage myDP.getItemAt(index) Parameters index A number greater than or equal to 0 and less than DataProvider.length. This number is the index of the item to retrieve. Returns
A reference to the retrieved item; undefined if the index is out of range. Description
Method; retrieves a reference to the item at a specified position. Example
The following code displays the label of the fifth item: trace(myDP.getItemAt(4).label);
DataProvider.getItemID() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004 Professional. Usage myDP.getItemID(index) Parameters index
A number greater than or equal to 0.
Returns
A number that is the unique ID of the item. Description
Method; returns a unique ID for the item. This method is primarily used to track selection. The ID is used in data-aware components to keep lists of what items are selected. Example
This example gets the ID of the fourth item: var ID = myDP.getItemID(3);
294
Chapter 6: Components Dictionary
DataProvider.length Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDP.length Description
Property (read-only); the number of items in the data provider. Example
This example sends the number of items in the myArray data provider to the Output panel: trace(myArray.length);
DataProvider.modelChanged Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage listenerObject = new Object(); listenerObject.modelChanged = function(eventObject){ // insert your code here } myMenu.addEventListener("modelChanged", listenerObject) Description
Event; broadcast to all of its view listeners whenever the data provider is modified. You typically add a listener to a model by assigning its dataProvider property. Version 2 components use a dispatcher/listener event model. When a data provider changes in some way, it broadcasts a modelChanged event, and data-aware components catch it to update their displays to reflect the changes in data. The Menu.modelChanged event’s event object has five additional properties:
•
eventName The eventName property is used to subcategorize modelChanged events. Data-aware components use this information to avoid completely refreshing the component instance (view) that is using the data provider. The eventName property supports the following values: ■
updateAll
■
addItems
The entire view needs refreshing, excluding scroll position. A series of items has been added.
DataProvider API
295
■
removeItems
A series of items has been deleted.
■
updateItems
A series of items needs refreshing.
■
sort
■
updateField
■
updateColumn
■
The data has been sorted.
filterModel
A field in an item must be changed and needs refreshing. An entire field’s definition in the data provider needs refreshing. The model has been filtered, and the view needs refreshing (reset the scroll
position). ■
• •
schemaLoaded
lastItem
The field’s definition of the data provider has been declared.
The index of the first affected item.
firstItem
The index of the last affected item. The value equals firstItem if only one item is
affected.
• •
removedIDs fieldName
An array of the item identifiers that were removed. A string indicating the name of the field that is affected.
For more information, see “EventDispatcher class” on page 415. Example
In the following example, a handler called listener is defined and passed to addEventListener() as the second parameter. The event object is captured by the modelChanged handler in the evt parameter. When the modelChanged event is broadcast, a trace statement is sent to the Output panel. listener = new Object(); listener.modelChanged = function(evt){ trace(evt.eventName); } myList.addEventListener("modelChanged", listener);
DataProvider.removeAll() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDP.removeAll() Parameters
None. Returns
Nothing.
296
Chapter 6: Components Dictionary
Description
Method; removes all items in the data provider. This method triggers the modelChanged event with the event name removeItems. Example
This example removes all the items in the data provider: myDP.removeAll();
DataProvider.removeItemAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDP.removeItemAt(index) Parameters index
A number greater than or equal to 0. This number is the index of the item to remove.
Returns
Nothing. Description
Method; removes the item at the specified index. The indices after the removed index collapse by one. This method triggers the modelChanged event with the event name removeItems. Example
This example removes the item at the fourth position: myDP.removeItemAt(3);
DataProvider.replaceItemAt() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDP.replaceItemAt(index, item)
DataProvider API
297
Parameters
A number greater than or equal to 0. This number is the index of the item to change.
index item
An object that is the new item.
Returns
Nothing. Description
Method; replaces the content of the item at the specified index. This method triggers the modelChanged event with the event name removeItems. Example
This example replaces the item at index 3 with the item labeled “new label”: myDP.replaceItemAt(3, {label : "new label"});
DataProvider.sortItems() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage myDP.sortItems([compareFunc], [optionsFlag]) Parameters
A reference to a function that compares two items to determine their sort order. For details, see Array.sort() in Flash ActionScript Language Reference.This parameter is optional. compareFunc
optionsFlag Lets you perform multiple, different types of sorts on a single array without having to replicate the entire array or resort it repeatedly. This parameter is optional.
The following are possible values for optionsFlag:
298
• • •
Array.DESCENDING,
•
Array.UNIQUESORT, which returns an error code (0) instead of a sorted array if two objects in the array are identical or have identical sort fields.
which sorts highest to lowest.
Array.CASEINSENSITIVE,
which sorts case-insensitively.
Array.NUMERIC,
which sorts numerically if the two elements being compared are numbers. If they aren’t numbers, use a string comparison (which can be case-insensitive if that flag is specified).
Chapter 6: Components Dictionary
•
Array.RETURNINDEXEDARRAY,
which returns an integer index array that is the result of the sort. For example, the following array would return the second line of code and the array would remain unchanged:
["a", "d", "c", "b"] [0, 3, 2, 1]
You can combine these options into one value. For example, the following code combines options 3 and 1: array.sort (Array.NUMERIC | Array.DESCENDING) Returns
Nothing. Description
Method; sorts the items in the data provider according to the specified compare function or according to one or more specified sort options. This method triggers the modelChanged event with the event name sort. Example
This example sorts according to uppercase labels. The items a and b are passed to the function and contain label and data fields: myList.sortItems(upperCaseFunc); function upperCaseFunc(a,b){ return a.label.toUpperCase() > b.label.toUpperCase(); }
DataProvider.sortItemsBy() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage myDP.sortItemsBy(fieldName, optionsFlag) myDP.sortItemsBy(fieldName, order) Parameters
A string that specifies the name of the field to use for sorting. This value is usually or "data".
fieldName "label"
A string that specifies whether to sort the items in ascending order ("ASC") or descending order ("DESC").
order
optionsFlag Lets you perform multiple, different types of sorts on a single array without having to replicate the entire array or resort it repeatedly. This parameter is optional.
DataProvider API
299
The following are possible values for optionsFlag:
• • •
Array.DESCENDING—sorts
•
Array.UNIQUESORT—if two objects in the array are identical or have identical sort fields, this method returns an error code (0) instead of a sorted array.
•
Array.RETURNINDEXEDARRAY—returns an integer
highest to lowest.
Array.CASEINSENSITIVE—sorts
case-insensitively.
Array.NUMERIC—sorts
numerically if the two elements being compared are numbers. If they aren’t numbers, use a string comparison (which can be case-insensitive if that flag is specified).
index array that is the result of the sort. For example, the following array would return the second line of code and the array would remain unchanged:
["a", "d", "c", "b"] [0, 3, 2, 1]
You can combine these options into one value. For example, the following code combines options 3 and 1: array.sort (Array.NUMERIC | Array.DESCENDING) Returns
Nothing. Description
Method; sorts the items in the data provider in the specified order, using the specified field name. If the fieldName items are a combination of text strings and integers, the integer items are listed first. The fieldName parameter is usually "label" or "data", but advanced programmers may specify any primitive value. This method triggers the modelChanged event with the event name sort. This is the fastest way to sort data in a component. It also maintains the component’s selection state. The sortItemsBy() method is fast because it doesn’t run any ActionScript while sorting. The sortItems() method needs to run an ActionScript compare function, and is therefore slower. Example
The following code sorts the items in a list in ascending order using the labels of the list items: myDP.sortItemsBy("label", "ASC");
300
Chapter 6: Components Dictionary
CHAPTER 6 Components Dictionary
DataSet component (Flash Professional only)
The DataSet component lets you work with data as collections of objects that can be indexed, sorted, searched, filtered, and modified. The DataSet component functionality includes DataSetIterator, a set of methods for traversing and manipulating a data collection, and DeltaPacket, a set of interfaces and classes for working with updates to a data collection. In most cases, you don’t use these classes and interfaces directly; you use them indirectly through methods provided by the DataSet class. The items managed by the DataSet component are also called transfer objects. A transfer object exposes business data that resides on the server with public attributes or accessor methods for reading and writing data. The DataSet component allows developers to work with sophisticated client-side objects that mirror their server-side counterparts or, in its simplest form, a collection of anonymous objects with public attributes that represent the fields in a record of data. For details on transfer objects, see Core J2EE Patterns Transfer Object at http://java.sun.com/blueprints/ corej2eepatterns/Patterns/TransferObject.html. Note: The DataSet component requires Flash Player 7 or later.
Using the DataSet component You typically use the DataSet component in combination with other components to manipulate and update a data source: a connector component for connecting to an external data source, user interface components for displaying data from the data source, and a resolver component for translating updates made to the data set into the appropriate format for sending to the external data source. You can then use data binding to bind properties of these different components together. The DataSet component uses functionality in the data binding classes. If you intend to work with the DataSet component in ActionScript only, without using the Binding and Schema tabs in the Component inspector to set properties, you’ll need to import the data binding classes into your FLA file and set required properties in your code. See “Making data binding classes available at runtime (Flash Professional only)” on page 213. For general information on how to manage data in Flash using the DataSet component, see “Data management (Flash Professional only)” in Using Flash. DataSet parameters You can set the following parameters for the DataSet component: itemClassName is a string indicating the name of the transfer object class that is instantiated each time a new item is created in the DataSet component.
The DataSet component uses transfer objects to represent the data that you retrieve from an external data source. If you leave this parameter blank, the data set creates an anonymous transfer object for you. If you give this parameter a value, the data set instantiates your transfer object whenever new data is added. Note: You must make a fully qualified reference to this class somewhere in your code to make sure that it gets compiled into your application (such as private var myItem:my.package.myItem;).
DataSet component (Flash Professional only)
301
logChanges is a Boolean value that defaults to true. If this parameter is set to true, the data set logs all changes made to its data and any method calls made on the associated transfer objects. readOnly is a Boolean value that defaults to false. If this parameter is set to true, the data set cannot be modified.
You can write ActionScript to control these and additional options for the DataSet component using its properties, methods, and events. For more information, see “DataSet class (Flash Professional only)” on page 304. Common workflow for the DataSet component The typical workflow for the DataSet component is as follows. To use a DataSet component:
1. Add an instance of the DataSet component to your application and give it an instance name. 2. Select the Schema tab for the DataSet component and create component properties to represent
the persistent fields of the data set. 3. Load the DataSet component with data from an external data source. (For more information,
see “About loading data into the DataSet component” in Using Flash.) 4. Use the Bindings tab of the Component inspector to bind the data set fields to UI components
in your application. The UI controls are notified as records (transfer objects) are selected or modified within the DataSet component, and updated accordingly. In addition, the DataSet component is notified of changes made from within a UI control; those changes are tracked by the data set and can be extracted by means of a delta packet. 5. Call the methods of the DataSet component in your application to manage your data. Note: In addition to these steps, you can bind the DataSet component to a connector and a resolver component to provide a complete solution for accessing, managing, and updating data from an external data source.
Creating an application with the DataSet component Typically, you use the DataSet component with other user interface components, and often with a connector component such as XMLConnector or WebServiceConnector. The items in the data set are populated by means of the connector component or raw ActionScript data, and then bound to user interface controls (such as List or DataGrid components). The DataSet component uses functionality in the data binding classes. If you intend to work with the DataSet component in ActionScript only, without using the Binding and Schema tabs in the Component inspector to set properties, you’ll need to import the data binding classes into your FLA file and set required properties in your code. See “Making data binding classes available at runtime (Flash Professional only)” on page 213.
302
Chapter 6: Components Dictionary
To create an application using the DataSet component:
1. In Flash MX Professional 2004, select File > New. In the Type column, select Flash Document
and click OK. 2. Open the Components panel if it’s not already open. 3. Drag a DataSet component from the Components panel to the Stage. In the Property inspector,
give it the instance name userData. 4. Drag a DataGrid component to the Stage and give it the instance name userGrid. 5. Resize the DataGrid component to be approximately 300 pixels wide and 100 pixels tall. 6. Drag a Button component to the Stage and set its instance name to nextBtn. 7. In the Timeline, select the first frame on Layer 1 and open the Actions panel. 8. Add the following code to the Actions panel: var recData = [{id:0, firstName:"Mick", lastName:"Jones"}, {id:1, firstName:"Joe", lastName:"Strummer"}, {id:2, firstName:"Paul", lastName:"Simonon"}]; userData.items = recData;
This populates the DataSet object’s items property with an array of objects, each of which has three properties: id, firstName, and lastName. 9. Add the three properties and their required data types to the DataSet schema: a Select the DataSet component on the Stage, open the Component inspector, and click the
Schema tab. b Click Add Component Property, and add three new properties, with field names id, firstName,
and lastName, and data types Number, String, and String, respectively.
Or, if you prefer to add the properties and their required data types in code, you can add the following line of code to the Actions panel instead of following steps a and b above: // add required schema types var i:mx.data.types.Str; var j:mx.data.types.Num;
10. To bind the contents of the DataSet component to the contents of the DataGrid component,
open the Component inspector and click the Bindings tab. 11. Select the DataGrid component (userGrid) on the Stage, and click the Add Binding (+) button
in the Component inspector. 12. In the Add Binding dialog box, select “dataProvider : Array” and click OK. 13. Double-click the Bound To field in the Component inspector. 14. In the Bound To dialog box that appears, select “DataSet <userData>” from the Component
Path column and then select “dataProvider : Array” from the Schema Location column. 15. To bind the selected index of the DataSet component to the selected index of the DataGrid
component, select the DataGrid component on the Stage and click the Add Binding (+) button again in the Component inspector. 16. In the dialog box that appears, select “selectedIndex : Number”. Click OK.
DataSet component (Flash Professional only)
303
17. Double-click the Bound To field in the Component inspector to open the Bound To dialog
box. 18. In the Component Path field, select “DataSet <userData>” from the Component Path column,
and then select “selectedIndex : Number” from the Schema Location column. 19. Enter the following code in the Actions panel: nextBtn.addEventListener("click", nextBtnClick); function nextBtnClick(eventObj:Object):Void { userData.next(); }
This code uses the DataSet.next() method to navigate to the next item in the DataSet object’s collection of items. Since you had previously bound the selectedIndex property of the DataGrid object to the same property of the DataSet object, changing the current item in the DataSet object will change the current (selected) item in the DataGrid object, as well. 20. Save the file, and select Control > Test Movie to test the SWF file.
The DataGrid object is populated with the specified items. Notice how clicking the button changes the selected item in the DataGrid object. DataSet class (Flash Professional only) Inheritance
MovieClip > DataSet
ActionScript Class Name
mx.data.components.DataSet
The DataSet component lets you work with data as collections of objects that can be indexed, sorted, searched, filtered, and modified. The DataSet component functionality includes DataSetIterator, a set of methods for traversing and manipulating a data collection, and DeltaPacket, a set of interfaces and classes for working with updates to a data collection. In most cases, you don’t use these classes and interfaces directly; you use them indirectly through methods provided by the DataSet class. Method summary for the DataSet class The following table lists the methods of the DataSet class.
304
Method
Description
DataSet.addItem()
Adds the specified item to the collection.
DataSet.addItemAt()
Adds an item to the data set at the specified position.
DataSet.addSort()
Creates a new sorted view of the items in the collection.
DataSet.applyUpdates()
Signals that the deltaPacket property has a value that you can access using data binding or ActionScript.
DataSet.changesPending()
Indicates whether the collection has changes pending that have not yet been sent in a delta packet.
DataSet.clear()
Clears all items from the current view of the collection.
DataSet.createItem()
Returns a newly initialized collection item.
Chapter 6: Components Dictionary
Method
Description
DataSet.disableEvents()
Stops sending DataSet events to listeners.
DataSet.enableEvents()
Resumes sending DataSet events to listeners.
DataSet.find()
Locates an item in the current view of the collection.
DataSet.findFirst()
Locates the first occurrence of an item in the current view of the collection.
DataSet.findLast()
Locates the last occurrence of an item in the current view of the collection.
DataSet.first()
Moves to the first item in the current view of the collection.
DataSet.getItemId()
Returns the unique ID for the specified item.
DataSet.getIterator()
Returns a clone of the current iterator.
DataSet.getLength()
Returns the number of items in the data set.
DataSet.hasNext()
Indicates whether the current iterator is at the end of its view of the collection.
DataSet.hasPrevious()
Indicates whether the current iterator is at the beginning of its view of the collection.
DataSet.hasSort()
Indicates whether the specified sort exists.
DataSet.isEmpty()
Indicates whether the collection contains any items.
DataSet.last()
Moves to the last item in the current view of the collection.
DataSet.loadFromSharedObj() Loads all of the relevant data needed to restore the DataSet
collection from a shared object. DataSet.locateById()
Moves the current iterator to the item with the specified ID.
DataSet.next()
Moves to the next item in the current view of the collection.
DataSet.previous()
Moves to the previous item in the current view of the collection.
DataSet.removeAll()
Removes all the items from the collection.
DataSet.removeItem()
Removes the specified item from the collection.
DataSet.removeItemAt()
Removes a data set item at a specified position.
DataSet.removeRange()
Removes the current iterator’s range settings.
DataSet.removeSort()
Removes the specified sort from the DataSet object.
DataSet.saveToSharedObj()
Saves the data in the DataSet object to a shared object.
DataSet.setIterator()
Sets the current iterator for the DataSet object.
DataSet.setRange()
Sets the current iterator’s range settings.
DataSet.skip()
Moves forward or backward by a specified number of items in the current view of the collection.
DataSet.useSort()
Makes the specified sort the active one.
DataSet component (Flash Professional only)
305
Property summary for the DataSet class The following table lists the properties of the DataSet class. Property
Description
DataSet.currentItem
Returns the current item in the collection.
DataSet.dataProvider
Returns the data provider.
DataSet.deltaPacket
Returns changes made to the collection, or assigns changes to be made to the collection.
DataSet.filtered
Indicates whether items are filtered.
DataSet.filterFunc
User-defined function for filtering items in the collection.
DataSet.items
Items in the collection.
DataSet.itemClassName
Name of the object to create when assigning items.
DataSet.length
Specifies the number of items in the current view of the collection.
DataSet.logChanges
Indicates whether changes made to the collection, or its items, are recorded.
DataSet.properties
Contains the properties (fields) for any transfer object in this collection.
DataSet.readOnly
Indicates whether the collection can be modified.
DataSet.schema
Specifies the collection’s schema in XML format.
DataSet.selectedIndex
Contains the current item’s index in the collection.
Event summary for the DataSet class The following table lists the events of the DataSet class.
306
Event
Description
DataSet.addItem
Broadcast before an item is added to the collection.
DataSet.afterLoaded
Broadcast after the items property is assigned.
DataSet.calcFields
Broadcast when calculated fields should be updated.
DataSet.deltaPacketChanged
Broadcast when the DataSet object’s delta packet has been changed and is ready to be used.
DataSet.iteratorScrolled
Broadcast when the iterator’s position is changed.
DataSet.modelChanged
Broadcast when items in the collection have been modified in some way.
DataSet.newItem
Broadcast when a new transfer object is constructed by the DataSet object, but before it is added to the collection.
DataSet.removeItem
Broadcast before an item is removed.
DataSet.resolveDelta
Broadcast when a delta packet is assigned to the DataSet object that contains messages.
Chapter 6: Components Dictionary
DataSet.addItem Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage on(addItem) { // insert your code here } listenerObject = new Object(); listenerObject.addItem = function (eventObj) { // insert your code here } dataSet.addEventListener("addItem", listenerObject) Description
Event; generated just before a new record (transfer object) is inserted into this collection. If you set the result property of the event object to false, the add operation is canceled; if you set it to true, the add operation is allowed. The event object (eventObj) contains the following properties: target
The DataSet object that generated the event.
type
The string "addItem".
item
A reference to the item in the collection to be added.
result A Boolean value that specifies whether the specified item should be added. By default, this value is true. Example
The following on(addItem) event handler (attached to a DataSet object) cancels the addition of the new item if a user-defined function named userHasAdminPrivs() returns false; otherwise, the item addition is allowed. on(addItem) { if(globalObj.userHasAdminPrivs()) { // Allow the item addition. eventObj.result = true; } else { // Don’t allow item addition; user doesn’t have admin privileges. eventObj.result = false; } } See also DataSet.removeItem
DataSet component (Flash Professional only)
307
DataSet.addItem() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.addItem([obj]) Parameters obj
An object to add to this collection. This parameter is optional.
Returns
A Boolean value: true if the item was added to the collection, false if it was not. Description
Method; adds the specified record (transfer object) to the collection for management. The newly added item becomes the current item of the data set. If no obj parameter is specified, a new object is created automatically by means of DataSet.createItem(). The location of the new item in the collection depends on whether a sort has been specified for the current iterator. If no sort is in use, the item is added to the end of the collection. If a sort is in use, the item is added to the collection according to its position in the current sort. For more information on initialization and construction of the transfer object, see DataSet.createItem(). Example
The following example uses DataSet.createItem() to create a new item and add it to the data set: myDataSet.addItem(myDataSet.createItem()); See also DataSet.createItem()
DataSet.addItemAt() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage DataSetInstance.addItemAt(index, item)
308
Chapter 6: Components Dictionary
Parameters index A number greater than or equal to 0. This number indicates the position at which to insert the item; it is the index of the new item. item
An object containing the data for the item.
Returns
A Boolean value indicating whether the item was added: true indicates that the item was added, and false indicates that the item already exists in the data set. Description
Method; adds a new item to the data set at the specified index. Indices greater than the data provider’s length are ignored. This method triggers the modelChanged event with the event name addItems. Example
The following example adds an item to the data set myDataSet at the fourth position: myDataset.addItemAt(3, {label : "this is the fourth item"});
DataSet.addSort() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.addSort(name, fieldList, sortOptions) Parameters name
A string that specifies the name of the sort.
fieldList
An array of strings that specify the field names to sort on.
sortOptions One or more of the following integer (constant) values, which indicate what options are used for this sort. Separate multiple values using the bitwise OR operator (|). Specify one or more of the following values:
•
DataSetIterator.Ascending
Sorts items in ascending order. This is the default sort option,
if none is specified.
•
DataSetIterator.Descending
Sorts items in descending order based on item
properties specified.
• •
DataSetIterator.Unique
Prevents the sort if any fields have like values.
Ignores case when comparing two strings during the sort operation. By default, sorts are case-sensitive when the property being sorted on is a string.
DataSetIterator.CaseInsensitive
DataSet component (Flash Professional only)
309
A DataSetError exception is thrown when DataSetIterator.Unique is specified as a sort option and the data being sorted is not unique, when the specified sort name has already been added, or when a property specified in the fieldList array does not exist in this data set. Returns
Nothing. Description
Method; creates a new ascending or descending sort for the current iterator based on the properties specified by the fieldList parameter. Flash automatically assigns the new sort to the current iterator after it is created, and then stores it in the sorting collection for later retrieval. Example
The following code creates a new sort named "rank" that performs a descending, case-sensitive, unique sort on the DataSet object’s "classRank" field. myDataSet.addSort("rank", ["classRank"], DataSetIterator.Descending | DataSetIterator.Unique | DataSetIterator.CaseInsensitive); See also DataSet.removeSort()
DataSet.afterLoaded Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage on(afterLoaded) { // insert your code here } listenerObject = new Object(); listenerObject.afterLoaded = function (eventObj) { // insert your code here } dataSet.addEventListener("afterLoaded", listenerObject) Description
Event; broadcast immediately after the DataSet.items property has been assigned. The event object (eventObj) contains the following properties: target type
310
The DataSet object that generated the event. The string "afterLoaded".
Chapter 6: Components Dictionary
Example
In this example, a form named contactForm (not shown) is made visible once the items in the data set contact_ds have been assigned. contact_ds.addEventListener("afterLoaded", loadListener); loadListener = new Object(); loadListener.afterLoaded = function (eventObj) { if(eventObj.target == "contact_ds") { contactForm.visible = true; } }
DataSet.applyUpdates() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.applyUpdates() Parameters
None. Returns
Nothing. Description
Method; signals that the DataSet.deltaPacket property has a value that you can access using data binding or directly by ActionScript. Before this method is called, the DataSet.deltaPacket property is null. This method has no effect if events have been disabled by means of the DataSet.disableEvents() method. Calling this method also creates a transaction ID for the current DataSet.deltaPacket property and emits a deltaPacketChanged event. For more information, see DataSet.deltaPacket. Example
The following code calls the applyUpdates() method on myDataSet. myDataSet.applyUpdates(); See also DataSet.deltaPacket
DataSet component (Flash Professional only)
311
DataSet.calcFields Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage on(calcFields) { // insert your code here } listenerObject = new Object(); listenerObject.calcFields = function (eventObj) { // insert your code here } dataSet.addEventListener("calcFields", listenerObject) Description
Event; generated when values of calculated fields for the current item in the collection need to be determined. A calculated field is one whose Kind property is set to Calculated on the Schema tab of the Component inspector. The calcFields event listener that you create should perform the required calculation and set the value for the calculated field. This event is also called when the value of a noncalculated field (that is, a field with its Kind property set to Data on the Schema tab) is updated. For more information on the Kind property, see “Schema kinds” in Using Flash. Caution: Do not change the values of any of noncalculated fields in this event, because this will result in an “infinite loop.” Set only the values of calculated fields within the calcFields event.
DataSet.changesPending() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.changesPending() Parameters
None. Returns
A Boolean value.
312
Chapter 6: Components Dictionary
Description
Method; returns true if the collection, or any item in the collection, has changes pending that have not yet been sent in a delta packet; otherwise, returns false. Example
The following code enables a Save Changes button (not shown) if the DataSet collection, or any items with that collection, have had modifications made to them that haven’t been committed to a delta packet. if(data_ds.changesPending()) { saveChanges_btn.enabled = true; }
DataSet.clear() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.clear() Returns
Nothing. Description
Method; removes the items in the current view of the collection. Which items are considered “viewable” depends on any current filter and range settings on the current iterator. Therefore, calling this method might not clear all of the items in the collection. To clear all of the items in the collection regardless of the current iterator’s view, use DataSet.removeAll(). If DataSet.logChanges is set to true when you invoke this method, “remove” entries are added to DataSet.deltaPacket for all items in the collection. Example
This example removes all items from the current view of the DataSet collection. Because the logChanges property is set to true, the removal of those items is logged. myDataSet.logChanges= true; myDataSet.clear(); See also DataSet.deltaPacket, DataSet.logChanges
DataSet component (Flash Professional only)
313
DataSet.createItem() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.createItem([itemData]) Parameters itemData
Data associated with the item. This parameter is optional.
Returns
The newly constructed item. Description
Method; creates an item that isn’t associated with the collection. You can specify the class of object created by using the DataSet.itemClassName property. If no DataSet.itemClassName value is specified and the itemData parameter is omitted, an anonymous object is constructed. This anonymous object’s properties are set to the default values based on the schema currently specified by DataSet.schema. When this method is invoked, any listeners for the DataSet.newItem event are notified and are able to manipulate the item before it is returned by this method. The optional item data is used to initialize the class specified with the DataSet.itemClassName property or is used as the item if DataSet.itemClassName is blank. A DataSetError exception is thrown when the class specified with the DataSet.itemClassName property cannot be loaded. Example contact.itemClassName = "Contact"; var itemData = new XML("John Smith555.555.4567<pre>94025<post>0556"); contact.addItem(contact.createItem(itemData)); See also DataSet.itemClassName, DataSet.newItem, DataSet.schema
DataSet.currentItem Availability
Flash Player 7. Edition
Flash MX Professional 2004.
314
Chapter 6: Components Dictionary
Usage dataSet.currentItem Description
Property (read-only); returns the current item in the DataSet collection, or null if the collection is empty or if the current iterator’s view of the collection is empty. This property provides direct access to the item in the collection. Changes made by directly accessing this object are not tracked (in the DataSet.deltaPacket property), nor are any of the schema settings applied to any properties of this object. Example
The following example displays the value of the customerName property defined in the current item in the data set named customerData. trace(customerData.currentItem.customerName);
DataSet.dataProvider Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.dataProvider Description
Property; the data provider for this data set. This property provides data to user interface controls, such as the List and DataGrid components. For more information about the DataProvider API, see “DataProvider API” on page 290. Example
The following code assigns the dataProvider property of a DataSet object to the corresponding property of a DataGrid component. myGrid.dataProvider = myDataSet.dataProvider;
DataSet.deltaPacket Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.deltaPacket
DataSet component (Flash Professional only)
315
Description
Property; returns a delta packet that contains all of the change operations made to the dataSet collection and its items. This property is null until DataSet.applyUpdates() is called on dataSet. When DataSet.applyUpdates() is called, a transaction ID is assigned to the delta packet. This transaction ID is used to identify the delta packet on an update round trip from the server and back to the client. Any subsequent assignment to the deltaPacket property by a delta packet with a matching transaction ID is assumed to be the server’s response to the changes previously sent. A delta packet with a matching ID is used to update the collection and report errors specified within the packet. Errors or server messages are reported to listeners of the DataSet.resolveDelta event. Note that the DataSet.logChanges settings are ignored when a delta packet with a matching ID is assigned to DataSet.deltaPacket. A delta packet without a matching transaction ID updates the collection, as if the DataSet API were used directly. This may create additional delta entries, depending on the current DataSet.logChanges setting of dataSet and the delta packet. A DataSetError exception is thrown if a delta packet is assigned with a matching transaction ID and one of the items in the newly assigned delta packet cannot be found in the original delta packet. See also DataSet.applyUpdates(), DataSet.logChanges, DataSet.resolveDelta
DataSet.deltaPacketChanged Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage on(deltaPacketChanged) { // insert your code here } listenerObject = new Object(); listenerObject.deltaPacketChanged = function (eventObj) { // insert your code here } dataSet.addEventListener("deltaPacketChanged", listenerObject) Description
Event; broadcast when the specified DataSet object’s deltaPacket property has been changed and is ready to be used. See also DataSet.deltaPacket
316
Chapter 6: Components Dictionary
DataSet.disableEvents() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.disableEvents() Returns
Nothing. Description
Method; disables events for the DataSet object. While events are disabled, no user interface controls (such as a DataGrid component) are updated when changes are made to items in the collection, or when the DataSet object is scrolled to another item in the collection. To reenable events, you must call DataSet.enableEvents(). The disableEvents() method can be called multiple times, and enableEvents() must be called an equal number of times to reenable the dispatching of events. Example
In this example, events are disabled before changes are made to items in the collection, so the DataSet object won’t try to refresh controls and impact performance. // Disable events for the data set myDataSet.disableEvents(); myDataSet.last(); while(myDataSet.hasPrevious()) { var price = myDataSet.price; price = price * 0.5; // Everything's 50% off! myDataSet.price = price; myDataSet.previous(); } // Tell the data set it's time to update the controls now myDataSet.enableEvents(); See also DataSet.enableEvents()
DataSet.enableEvents() Availability
Flash Player 7. Edition
Flash MX Professional 2004.
DataSet component (Flash Professional only)
317
Usage dataSet.enableEvents() Returns
Nothing. Description
Method; reenables events for the DataSet objects after events have been disabled by a call to DataSet.disableEvents(). To reenable events for the DataSet object, the enableEvents() method must be called an equal or greater number of times than disableEvents() was called. Example
In this example, events are disabled before changes are made to items in the collection, so the DataSet object won’t try to refresh controls and impact performance. // Disable events for the data set myDataSet.disableEvents(); myDataSet.last(); while(myDataSet.hasPrevious()) { var price = myDataSet.price; price = price * 0.5; // Everything's 50% off! myDataSet.price = price; myDataSet.previous(); } // Tell the dataset it's time to update the controls now myDataSet.enableEvents(); See also DataSet.disableEvents()
DataSet.filtered Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.filtered Description
Property; a Boolean value that indicates whether the data in the current iterator is filtered. The default value is false.When this property is true, the filter function specified by DataSet.filterFunc is called for each item in the collection.
318
Chapter 6: Components Dictionary
Example
In the following example, filtering is enabled on the DataSet object named employee_ds. Suppose that each record in the DataSet collection contains a field named empType. The following filter function returns true if the empType field in the current item is set to "management"; otherwise, it returns false. employee_ds.filtered = true; employee_ds.filterFunc = function(item:Object) { // filter out employees who are managers... return(item.empType != "management"); } See also DataSet.filterFunc
Property; specifies a function that determines which items are included in the current view of the collection. When DataSet.filtered is set to true, the function assigned to this property is called for each record (transfer object) in the collection. For each item that is passed to the function, it should return true if the item should be included in the current view, or false if the item should not be included in the current view. When changing the filter function on a data set, you must set the filtered property to false and then true again in order for the proper modelChanged event to be generated. Changing the filterFunc property won’t generate the event. Also, if a filter is already in place when the data loads in (modelChanged or updateAll), the filter isn’t applied until filtered is set to false and then back to true again. Example
In the following example, filtering is enabled on the DataSet object named employee_ds. The specified filter function returns true if the empType field in each item is set to "management"; otherwise, it returns false. employee_ds.filtered = true; employee_ds.filterFunc = function(item:Object) { // filter out employees who are managers...
DataSet component (Flash Professional only)
319
return(item.empType != "management"); } See also DataSet.filtered
DataSet.find() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.find(searchValues) Parameters searchValues
An array that contains one or more field values to be found within the
current sort. Returns
Returns true if the values are found; otherwise, returns false. Description
Method; searches the current view of the collection for an item with the field values specified by searchValues. Which items are in the current view depends on any current filter and range settings. If an item is found, it becomes the current item in the DataSet object. The values specified by searchValues must be in the same order as the field list specified by the current sort (see the example below). If the current sort is not unique, the record (transfer object) found is nondeterministic. If you want to find the first or last occurrence of a transfer object in a nonunique sort, use DataSet.findFirst() or DataSet.findLast(). Conversion of the data specified is based on the underlying field’s type. For example, if you specify ["05-02-02"] as a search value, the underlying date field is used to convert the value using the date’s DataType.setAsString() method. If you specify [new Date().getTime()], the date’s DataType.setAsNumber() method is used. Example
This example searches for an item in the current collection whose name and id fields contain the values "Bobby" and 105, respectively. If found, DataSet.getItemId() is used to get the unique identifier for the item in the collection, and DataSet.locateById() is used to position the current iterator on that item. var studentID:String = null; studentData.addSort("id", ["name","id"]); // Locate the transfer object identified by "Bobby" and 105.
320
Chapter 6: Components Dictionary
// Note that the order of the search fields matches those // specified in addSort(). if(studentData.find(["Bobby", 105])) { studentID = studentData.getItemId(); } // Now use locateByID() to position the current iterator // on the item in the collection whose ID matches studentID. if(studentID != null) { studentData.locateById(studentID); } See also DataSet.applyUpdates(), DataSet.getItemId(), DataSet.locateById()
DataSet.findFirst() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.findFirst(searchValues) Parameters searchValues
An array that contains one or more field values to be found within the
current sort. Returns
Returns true if the items are found; otherwise, returns false. Description
Method; searches the current view of the collection for the first item with the field values specified by searchValues. Which items are in the current view depends on any current filter and range settings. The values specified by searchValues must be in the same order as the field list specified by the current sort (see the example below). Conversion of the data specified is based on the underlying field’s type. For example, if the search value specified is ["05-02-02"], the underlying date field is used to convert the value with the date’s setAsString() method. If the value specified is [new Date().getTime()], the date’s setAsNumber() method is used.
DataSet component (Flash Professional only)
321
Example
This example searches for the first item in the current collection whose name and age fields contain "Bobby" and "13". If found, DataSet.getItemId() is used to get the unique identifier for the item in the collection, and DataSet.locateById() is used to position the current iterator on that item. var studentID:String = null; studentData.addSort("nameAndAge", ["name", "age"]); // Locate the first transfer object with the specified values. // Note that the order of the search fields matches those // specified in addSort(). if(studentData.findFirst(["Bobby", "13"])) { studentID = studentData.getItemId(); } // Now use locateByID() to position the current iterator // on the item in the collection whose ID matches studentID. if(studentID != null) { studentData.locateById(studentID); } See also DataSet.applyUpdates(), DataSet.getItemId(), DataSet.locateById()
DataSet.findLast() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.findLast(searchValues) Parameters searchValues
An array that contains one or more field values to be found within the
current sort. Returns
Returns true if the items are found; otherwise, returns false. Description
Method; searches the current view of the collection for the last item with the field values specified by searchValues. Which items are in the current view depends on any current filter and range settings. The values specified by searchValues must be in the same order as the field list specified by the current sort (see the example below).
322
Chapter 6: Components Dictionary
Conversion of the data specified is based on the underlying field’s type. For example, if the search value specified is ["05-02-02"], the underlying date field is used to convert the value with the date’s setAsString() method. If the value specified is [new Date().getTime()], the date’s setAsNumber() method is used. Example
This example searches for the last item in the current collection whose name and age fields contain "Bobby" and "13". If found, DataSet.getItemId() is used to get the unique identifier for the item in the collection, and DataSet.locateById() is used to position the current iterator on that item. var studentID:String = null; studentData.addSort("nameAndAge", ["name", "age"]); // Locate the last transfer object with the specified values. // Note that the order of the search fields matches those // specified in addSort(). if(studentData.findLast(["Bobby", "13"])) { studentID = studentData.getItemId(); } // Now use locateByID() to position the current iterator // on the item in the collection whose ID matches studentID. if(studentID != null) { studentData.locateById(studentID); } See also DataSet.applyUpdates(), DataSet.getItemId(), DataSet.locateById()
DataSet.first() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.first() Returns
Nothing. Description
Method; makes the first item in the current view of the collection the current item. Which items are in the current view depends on any current filter and range settings.
DataSet component (Flash Professional only)
323
Example
The following code positions the data set inventoryData at the first item in its collection, and then displays the value of the price property contained by that item using the DataSet.currentItem property. inventoryData.first(); trace("The price of the first item is:" + inventoryData.currentItem.price); See also DataSet.last()
DataSet.getItemId() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.getItemId([index]) Parameters
A number specifying the item in the current view for which to get the ID. This parameter is optional.
index
Returns
A string. Description
Method; returns the identifier of the current item in the collection, or that of the item specified by index. This identifier is unique only in this collection and is assigned automatically by DataSet.addItem(). Example
The following code gets the unique ID for the current item in the collection and then displays it in the Output panel. var itemNo:String = myDataSet.getItemId(); trace("Employee id("+ itemNo+ ")"); See also DataSet.addItem()
DataSet.getIterator() Availability
Flash Player 7.
324
Chapter 6: Components Dictionary
Edition
Flash MX Professional 2004. Usage dataSet.getIterator() Returns
A ValueListIterator object. Description
Method; returns a new iterator for this collection; this iterator is a clone of the current iterator in use, including its current position in the collection. This method is mainly for advanced users who want access to multiple, simultaneous views of the same collection. Example myIterator:ValueListIterator = myDataSet.getIterator(); myIterator.sortOn(["name"]); myIterator.find({name:"John Smith"}).phone = "555-1212";
DataSet.getLength() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage DataSet.getLength() Returns
The number of items in the data set. Description
Method; returns the number of items in the data set. Example
The following example calls getLength(): //... var myDSet:mx.data.components.DataSet; myDSet = _parent.thisShelf.MyCompactDiscs; trace ("Data set size is: " + myDSet.getLength()); //...
DataSet.hasNext() Availability
Flash Player 7.
DataSet component (Flash Professional only)
325
Edition
Flash MX Professional 2004. Usage dataSet.hasNext() Returns
A Boolean value. Description
Method; returns false if the current iterator is at the end of its view of the collection; otherwise, returns true. Example
This example iterates over all of the items in the current view of the collection (starting at its beginning) and performs a calculation on the price property of each item. myDataSet.first(); while(myDataSet.hasNext()) { var price = myDataSet.currentItem.price; price = price * 0.5; // Everything's 50% off! myDataSet.currentItem.price = price; myDataSet.next(); } See also DataSet.currentItem, DataSet.first(), DataSet.next()
DataSet.hasPrevious() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.hasPrevious() Returns
A Boolean value. Description
Method; returns false if the current iterator is at the beginning of its view of the collection; otherwise, returns true. Example
This example iterates over all of the items in the current view of the collection (starting from the its last item) and performs a calculation on the price property of each item.
326
Chapter 6: Components Dictionary
myDataSet.last(); while(myDataSet.hasPrevious()) { var price = myDataSet.currentItem.price; price = price * 0.5; // Everything's 50% off! myDataSet.currentItem.price = price; myDataSet.previous(); } See also DataSet.currentItem, DataSet.skip(), DataSet.previous()
DataSet.hasSort() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.hasSort(sortName) Parameters sortName
A string that contains the name of a sort created with DataSet.addSort().
Returns
A Boolean value. Description
Method; returns true if the sort specified by sortName exists; otherwise, returns false. Example
The following code tests if a sort named “customerSort” exists. If the sort already exists, it is made the current sort by means of DataSet.useSort(). If a sort by that name doesn’t exist, one is created by means of DataSet.addSort(). if(myDataSet.hasSort("customerSort")){ myDataSet.useSort("customerSort"); } else { myDataSet.addSort("customerSort", ["customer"], DataSetIterator.Descending); } See also DataSet.addSort(), DataSet.applyUpdates(), DataSet.useSort()
DataSet component (Flash Professional only)
327
DataSet.isEmpty() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.isEmpty() Returns
A Boolean value. Description
Method; returns true if the specified DataSet object doesn’t contain any items (that is, if dataSet.length == 0). Example
The following code disables a Delete Record button (not shown) if the DataSet object it applies to is empty. if(userData.isEmpty()){ delete_btn.enabled = false; } See also DataSet.length
DataSet.items Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage myDataSet.items Description
Property; an array of items managed by myDataSet. Example
This example assigns an array of objects to a DataSet object’s items property. var recData = [{id:0, firstName:"Mick", lastName:"Jones"}, {id:1, firstName:"Joe", lastName:"Strummer"}, {id:2, firstName:"Paul", lastName:"Simonon"}]; myDataSet.items = recData;
328
Chapter 6: Components Dictionary
DataSet.itemClassName Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.itemClassName Description
Property; a string indicating the name of the class that should be created when items are added to the collection. The class you specify must implement the TransferObject interface, shown below. interface mx.data.to.TransferObject { function clone():Object; function getPropertyData():Object; function setPropertyData(propData:Object):Void; }
You can also set this property in the Property inspector. To make the specified class available at runtime, you must also make a fully qualified reference to this class somewhere in your SWF file’s code, as in the following code snippet: var myItem:my.package.myItem;
A DataSetError exception is thrown if you try to modify the value of this property after the DataSet.items array has been loaded. For more information, see “TransferObject interface” on page 756. DataSet.iteratorScrolled Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage on(iteratorScrolled) { // insert your code here } listenerObject = new Object(); listenerObject.iteratorScrolled = function (eventObj) { // insert your code here } dataSet.addEventListener("iteratorScrolled", listenerObject)
DataSet component (Flash Professional only)
329
Description
Event; generated immediately after the current iterator has scrolled to a new item in the collection. The event object (eventObj) contains the following properties: The DataSet object that generated the event.
target type
The string "iteratorScrolled".
scrolled A number that specifies how many items the iterator scrolled; positive values indicate that the iterator moved forward in the collection; negative values indicate that it moved backward in the collection. Example
In this example, the status bar of an application (not shown) is updated when the position of the current iterator changes. on(iteratorScrolled) { var dataSet:mx.data.components.DataSet = eventObj.target; var statusBarText = dataSet.fullname+" Acct #: "+dataSet.getField("acctnum").getAsString(); setStatusBar(statusBarText); }
DataSet.last() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.last() Returns
Nothing. Description
Method; makes the last item in the current view of the collection the current item. Example
The following code, attached to a Button component, goes to the last item in the DataSet collection. function goLast(eventObj:obj) { inventoryData.last(); } goLast_btn.addEventListener("click", goLast);
330
Chapter 6: Components Dictionary
See also DataSet.first()
DataSet.length Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.length Description
Property (read-only); specifies the number of items in the current view of the collection. The viewable number of items is based on the current filter and range settings. Example
The following example alerts users if they haven’t made enough entries in the data set, perhaps using an editable DataGrid component. if(myDataSet.length < MIN_REQUIRED) { alert("You need at least "+MIN_REQUIRED); }
DataSet.loadFromSharedObj() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.loadFromSharedObj(objName, [localPath]) Parameters objName A string specifying the name of the shared object to retrieve. The name can include forward slashes (for example, “work/addresses”). Spaces and the following characters are not allowed in the specified name: ~ % & \ ; : " ' , < > ? #
An optional string parameter that specifies the full or partial path to the SWF file that created the shared object. This string is used to determine where the object is stored on the user’s computer. The default value is the SWF file’s full path.
localPath
DataSet component (Flash Professional only)
331
Returns
Nothing. Description
Method; loads all of the relevant data needed to restore this DataSet collection from a shared object. To save a DataSet collection to a shared object, use DataSet.saveToSharedObj(). The DataSet.loadFromSharedObject() method overwrites any data or pending changes that might exist in this DataSet collection. Note that the instance name of the DataSet collection is used to identify the data in the specified shared object. This method throws a DataSetError exception if the specified shared object isn’t found or if there is a problem retrieving the data from it. Example
This example attempts to load a shared object named webapp/customerInfo associated with the data set named myDataSet. The method is called within a try...catch code block. try { myDataSet.loadFromSharedObj("webapp/customerInfo"); } catch(e:DataSetError) { trace("Unable to load shared object.”); } See also DataSet.saveToSharedObj()
DataSet.locateById() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.locateById(id) Parameters id
A string identifier for the item in the collection to be located.
Returns
A Boolean value. Description
Method; positions the current iterator on the collection item whose ID matches id. This method returns true if the specified ID can be matched to an item in the collection; otherwise, it returns false.
332
Chapter 6: Components Dictionary
Example
This example uses DataSet.find() to search for an item in the current collection whose name and id fields contain the values "Bobby" and 105, respectively. If found, DataSet.getItemId() is used to get the unique identifier for that item, and DataSet.locateById() is used to position the current iterator at that item. var studentID:String = null; studentData.addSort("id", ["name","id"]); if(studentData.find(["Bobby", 105])) { studentID = studentData.getItemId(); studentData.locateById(studentID); } See also DataSet.applyUpdates(), DataSet.find(), DataSet.getItemId()
DataSet.logChanges Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.logChanges Description
Property; a Boolean value that specifies whether changes made to the data set, or its items, should (true) or should not (false) be recorded in DataSet.deltaPacket. When this property is set to true, operations performed at the collection level and item level are logged. Collection-level changes include the addition and removal of items from the collection. Item-level changes include property changes made to items and method calls made on items by means of the DataSet component. Example
The following example disables logging for the DataSet object named userData. userData.logChanges = false; See also DataSet.deltaPacket
DataSet component (Flash Professional only)
333
DataSet.modelChanged Availability
Flash Player 7. Edition
Flash MX Professional 2004. Description on(modelChanged) { // insert your code here } listenerObject = new Object(); listenerObject.modelChanged = function (eventObj) { // insert your code here } dataSet.addEventListener("modelChanged", listenerObject) Description
Event; broadcast when the collection changes in some way—for example, when items are removed or added to the collection, when the value of an item’s property changes, or when the collection is filtered or sorted. The event object (eventObj) contains the following properties: The DataSet object that generated the event.
target type
The string "iteratorScrolled". The index (number) of the first item in the collection that was affected by
firstItem
the change. The index (number) of the last item in the collection that was affected by the change (equals firstItem if only one item was affected).
lastItem
fieldName undefined
A string that contains the name of the field being affected. This property is unless the change was made to a property of the DataSet object.
A string that describes the change that took place. This can be one of the following values:
eventName
334
String value
Description
"addItems"
A series of items has been added.
"filterModel"
The model has been filtered, and the view needs refreshing (reset scroll position).
"removeItems"
A series of items has been deleted.
"schemaLoaded"
The fields definition of the data provider has been declared.
"sort"
The data has been sorted.
"updateAll"
The entire view needs refreshing, excluding scroll position.
"updateColumn"
An entire field’s definition in the data provider needs refreshing.
Chapter 6: Components Dictionary
String value
Description
"updateField"
A field in an item has been changed and needs refreshing.
"updateItems"
A series of items needs refreshing.
Example
In this example, a Delete Item button is disabled if the items have been removed from the collection and the target DataSet object has no more items. on(modelChanged) { delete_btn.enabled = ((eventObj.eventName == "removeItems") && (eventObj.target.isEmpty())); } See also DataSet.isEmpty()
DataSet.newItem Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage on(newItem) { // insert your code here } listenerObject = new Object(); listenerObject.newItem = function (eventObj) { // insert your code here } dataSet.addEventListener("newItem", listenerObject) Description
Event; broadcast when a new transfer object is constructed by means of DataSet.createItem(). A listener for this event can make modifications to the item before it is added to the collection. The event object (eventObj) contains the following properties: target
The DataSet object that generated the event.
type
The string "iteratorScrolled".
item
A referenece to the item that was created.
Example
This example makes modifications to a newly created item before it’s added to the collection. function newItemEvent(evt:Object):Void { var employee:Object = evt.item;
DataSet component (Flash Professional only)
335
employee.name = "newGuy"; // property data happens to be XML employee.zip = employee.getPropertyData().firstChild.childNodes[1].attributes.zip; } employees_ds.addEventListener("newItem", newItemEvent);
DataSet.next() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.next() Returns
Nothing. Description
Method; makes the next item in the current view of the collection the current item. Which items are in the current view depends on any current filter and range settings. Example
This example loops over all the items in a DataSet object, starting from the first item, and performs a calculation on a field in each item. myDataSet.first(); while(myDataSet.hasNext()) { var price = myDataSet.price; price = price * 0.5; // Everything's 50% off! myDataSet.price = price; myDataSet.next(); } See also DataSet.first(), DataSet.hasNext()
DataSet.previous() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.previous()
336
Chapter 6: Components Dictionary
Returns
Nothing. Description
Method; makes the previous item in the current view of the collection the current item. Which items are in the current view depends on any current filter and range settings. This example loops over all the items in the current view of the collection, starting from the last item, and performs a calculation on a field in each item. myDataSet.last(); while(myDataSet.hasPrevious()) { var price = myDataSet.price; price = price * 0.5; // Everything's 50% off! myDataSet.price = price; myDataSet.previous(); } See also DataSet.first(), DataSet.hasNext()
DataSet.properties Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.properties Description
Property (read-only); returns an object that contains all of the exposed properties (fields) for any transfer object within this collection. Example
This example displays all the names of the properties in the DataSet object named myDataSet. for(var i in myDataSet.properties) { trace("field '"+i+ "' has value "+ myDataSet.properties[i]); }
DataSet.readOnly Availability
Flash Player 7. Edition
Flash MX Professional 2004.
DataSet component (Flash Professional only)
337
Usage dataSet.readOnly Description
Property; a Boolean value that specifies whether this collection can be modified (false) or is read-only (true). Setting this property to true prevents updates to the collection. The default value is false. You can also set this property in the Property inspector. Example
The following example makes the DataSet object named myDataSet read-only, and then attempts to change the value of a property that belongs to the current item in the collection. This will throw an exception. myDataSet.readOnly = true; // This will throw an exception myDataSet.currentItem.price = 15; See also DataSet.currentItem
DataSet.removeAll() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.removeAll() Parameters
None. Returns
Nothing. Description
Method; removes all items in the DataSet collection. Example
This example removes all the items in the DataSet collection contact_ds: contact_ds.removeAll();
338
Chapter 6: Components Dictionary
DataSet.removeItem Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage on(removeItem) { // insert your code here } listenerObject = new Object(); listenerObject.removeItem = function (eventObj) { // insert your code here } dataSet.addEventListener("removeItem", listenerObject) Description
Event; generated just before a new item is deleted from this collection. If you set the result property of the event object to false, the delete operation is canceled; if you set it to true, the delete operation is allowed. The event object (eventObj) contains the following properties: target
The DataSet object that generated the event.
type
The string "removeItem".
item
A reference to the item in the collection to be removed.
result A Boolean value that specifies whether the item should be removed. By default, this value is true. Example
In this example, an on(removeItem) event handler cancels the deletion of the new item if a user-defined function named userHasAdminPrivs() returns false; otherwise, the deletion is allowed. on(removeItem) { if(globalObj.userHasAdminPrivs()) { // Allow the item deletion. eventObj.result = true; } else { // Don’t allow item deletion; user doesn’t have admin privileges. eventObj.result = false; } } See also DataSet.addItem
DataSet component (Flash Professional only)
339
DataSet.removeItem() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.removeItem([item]) Parameters item
The item to be removed. This parameter is optional.
Returns
A Boolean value. Returns true if the item was successfully removed; otherwise, returns false. Description
Method; removes the specified item from the collection, or removes the current item if the item parameter is omitted. This operation is logged to DataSet.deltaPacket if DataSet.logChanges is true. Example
The following code, attached to an instance of the Button component, removes the current item in the DataSet object named usersData that resides on the same Timeline as the Button instance. on(click) { _parent.usersData.removeItem(); } See also DataSet.deltaPacket, DataSet.logChanges
DataSet.removeItemAt() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage DataSetInstance.removeItemAt(index) Parameters index
340
A number greater than or equal to 0. This number is the index of the item to remove.
Chapter 6: Components Dictionary
Returns
A Boolean value indicating whether the item was removed. Description
Method; removes the item at the specified index. The indices after the removed index collapse by one. This method triggers the modelChanged event with the event name removeItems. In addition, it triggers the DataSet.removeItem event, which contains the result and item properties. The result property is used to determine if the item (referenced by the item property of the event) can be removed. By default, the result property is set to true, or if no event listener is specified for the removeItem event, the item will be removed by default. An event listener can stop the item from being removed by listening for the removeItem event and setting the result property of the event to false, as shown in this example: function removeItem(eventObj:Object):Void { // don’t allow anyone to remove the item with customerId == 0 eventObj.result = eventObj.item.customerId != 0; } Example
This example removes an item from the data set at the fourth position: myDataSet.removeItemAt(3);
DataSet.removeRange() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.removeRange() Returns
Nothing. Description
Method; removes the current end point settings specified by DataSet.setRange() for the current iterator. Example myDataSet.addSort("name_id", ["name", "id"]); myDataSet.setRange(["Bobby", 105],["Cathy", 110]); while(myDataSet.hasNext()) { myDataSet.gradeLevel ="5"; // change all of the grades in this range myDataSet.next();
DataSet component (Flash Professional only)
341
} myDataSet.removeRange(); myDataSet.removeSort("name_id"); See also DataSet.applyUpdates(), DataSet.hasNext(), DataSet.next(), DataSet.removeSort(), DataSet.setRange()
DataSet.removeSort() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.removeSort(sortName) Parameters sortName
A string that specifies the name of the sort to remove.
Returns
Nothing. Description
Method; removes the specified sort from this DataSet object if the sort exists. If the specified sort does not exist, this method throws a DataSetError exception. Example myDataSet.addSort("name_id", ["name", "id"]); myDataSet.setRange(["Bobby", 105],["Cathy", 110]); while(myDataSet.hasNext()) { myDataSet.gradeLevel ="5"; // change all of the grades in this range myDataSet.next(); } myDataSet.removeRange(); myDataSet.removeSort("name_id"); See also DataSet.applyUpdates(), DataSet.hasNext(), DataSet.next(), DataSet.removeRange(), DataSet.setRange()
342
Chapter 6: Components Dictionary
DataSet.resolveDelta Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage on(resolveDelta) { // insert your code here } listenerObject = new Object(); listenerObject.resolveDelta = function (eventObj) { // insert your code here } dataSet.addEventListener("resolveDelta", listenerObject) Description
Event; broadcast when DataSet.deltaPacket is assigned a delta packet whose transaction ID matches that of a delta packet previously retrieved from the DataSet object, and that has messages associated with any of the deltas or DeltaItem objects contained by that delta packet. This event gives you the chance to reconcile any error returned from the server while attempting to apply changes previously submitted. Typically, you use this event to display a “reconcile dialog box” with the conflicting values, allowing the user to make appropriate modifications to the data so that it can be re-sent. The event object (eventObj) contains the following properties: target
The DataSet object that generated the event.
type
The string "resolveDelta".
data
An array of deltas and associated DeltaItem objects that have nonzero length messages.
Example
This example displays a form called reconcileForm (not shown) and calls a method on that form object (setReconcileData()) that allows the user to reconcile any conflicting values returned by the server. myDataSet.addEventListener("resolveDelta", resolveDelta); function resolveDelta(eventObj:Object) { reconcileForm.visible = true; reconcileForm.setReconcileData(eventObj.data); } // in the reconcileForm code function setReconcileData(data:Array):Void { var di:DeltaItem; var ops:Array = ["property", "method"]; var cl:Array; // change list var msg:String;
DataSet component (Flash Professional only)
343
for (var i = 0; i0) { trace("The following problem occurred '"+msg+"' while performing a '"+ops[di.kind]+"' modification on/with '"+di.name+"' current server value ["+di.curValue+"], value sent ["+di.newValue+"] Please fix!"); } } } }
DataSet.saveToSharedObj() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.saveToSharedObj(objName, [localPath]) Parameters
A string that specifies the name of the shared object to create. The name can include forward slashes (for example, “work/addresses”). Spaces and the following characters are not allowed in the specified name:
objName
~ % & \ ; : " ' , < > ? #
An optional string parameter that specifies the full or partial path to the SWF file that created the shared object. This string is used to determine where the object will be stored on the user’s computer. The default value is the SWF file’s full path.
localPath
Returns
Nothing. Description
Method; saves all of the relevant data needed to restore this DataSet collection to a shared object. This allows users to work when disconnected from the source data, if it is a network resource. This method overwrites any data that might exist within the specified shared object for this DataSet collection. To restore a DataSet collection from a shared object, use DataSet.loadFromSharedObj(). Note that the instance name of the DataSet collection is used to identify the data within the specified shared object. If the shared object can’t be created or there is a problem flushing the data to it, this method throws a DataSetError exception.
344
Chapter 6: Components Dictionary
Example
This example calls saveToSharedObj() in a try..catch block and displays an error if there is a problem saving the data to the shared object. try { myDataSet.saveToSharedObj("webapp/customerInfo"); } catch(e:DataSetError) { trace("Unable to create shared object”); } See also DataSet.loadFromSharedObj()
DataSet.schema Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.schema Description
Property; provides the XML representation of the schema for this DataSet object. The XML assigned to this property must have the following format: <properties> <property name="propertyName"> <encoder name="dataType"> format options <encoder/> <property> ... ...
A DataSetError exception is thrown if the XML specified does not follow the above format.
DataSet component (Flash Professional only)
345
Example
The following example sets the schema of the data set myDataSet to a new XML object containing appropriately formatted XML: myDataSet.schema = new XML("<properties><property name="billable"> ..etc.. ");
DataSet.selectedIndex Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.selectedIndex Description
Property; specifies the selected index in the collection. You can bind this property to the selected item in a DataGrid or List component, and vice versa. For a complete example that demonstrates this, see “Creating an application with the DataSet component” on page 302. Example
The following example sets the selected index of a DataSet object (userData) to the selected index in a DataGrid component (userGrid). userData.selectedIndex = userGrid.selectedIndex;
DataSet.setIterator() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.setIterator(iterator) Parameters iterator
An iterator object returned by a call to DataSet.getIterator().
Returns
Nothing.
346
Chapter 6: Components Dictionary
Description
Method; assigns the specified iterator to this DataSet object and makes it the current iterator. The specified iterator must come from a previous call to DataSet.getIterator() on the DataSet object to which it is being assigned; otherwise; a DataSetError exception is thrown. Example myIterator:ValueListIterator = myDataSet.getIterator(); myIterator.sortOn(["name"]); myDataSet.setIterator(myIterator); See also DataSet.getIterator()
DataSet.setRange() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.setRange(startValues, endValues) Parameters startValues endValues
An array of key values of the properties of the first transfer object in the range. An array of key values of the properties of the last transfer object in the range.
Returns
Nothing. Description
Method; sets the end points for the current iterator. The end points define a range in which the iterator operates. This is only valid if a valid sort has been set for the current iterator by means of DataSet.applyUpdates(). Setting a range for the current iterator is more efficient than using a filter function if you want a grouping of values (see DataSet.filterFunc). Example myDataSet.addSort("name_id", ["name", "id"]); myDataSet.setRange(["Bobby", 105],["Cathy", 110]); while(myDataSet.hasNext()) { myDataSet.gradeLevel ="5"; // change all of the grades in this range myDataSet.next(); } myDataSet.removeRange(); myDataSet.removeSort("name_id");
DataSet component (Flash Professional only)
347
See also DataSet.applyUpdates(), DataSet.hasNext(), DataSet.next(), DataSet.removeRange(), DataSet.removeSort()
DataSet.skip() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.skip(offSet) Parameters offSet
An integer specifying the number of records by which to move the iterator position.
Returns
Nothing. Description
Method; moves the current iterator’s position forward or backward in the collection by the amount specified by offSet. Positive offSet values move the iterator’s position forward; negative values move it backward. If the specified offset is beyond the beginning (or end) of the collection, the iterator is positioned at the beginning (or end) of the collection. Example
This example positions the current iterator at the first item in the collection, then moves to the next-to-last item and performs a calculation on a field belonging to that item. myDataSet.first(); // Move to the item just before the last one var itemsToSkip = myDataSet.length - 2; myDataSet.skip(itemsToSkip).price = myDataSet.amount * 10;
DataSet.useSort() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage dataSet.useSort(sortName, order)
348
Chapter 6: Components Dictionary
Parameters sortName order
A string that contains the name of the sort to use.
An integer value that indicates the sort order for the sort; the value must be or DataSetIterator.Descending.
DataSetIterator.Ascending Returns
Nothing. Description
Method; switches the sort for the current iterator to the one specified by sortName, if it exists. If the specified sort does not exist, a DataSetError exception is thrown. To create a sort, use DataSet.applyUpdates(). Example
This code uses DataSet.hasSort() to determine if a sort named "customer" exists. If it does, the code calls DataSet.useSort() to make "customer" the current sort. Otherwise, the code creates a sort by that name using DataSet.addSort(). if(myDataSet.hasSort("customer")) { myDataSet.useSort("customer"); } else { myDataSet.addSort("customer", ["customer"], DataSetIterator.Descending); } See also DataSet.applyUpdates(), DataSet.hasSort()
DataSet component (Flash Professional only)
349
CHAPTER 6 Components Dictionary
DateChooser component (Flash Professional only)
The DateChooser component is a calendar that allows users to select a date. It has buttons that allow users to scroll through months and click a date to select it. You can set parameters that indicate the month and day names, the first day of the week, and disabled dates, as well as highlighting the current date. A live preview of each DateChooser instance reflects the values indicated by the Property inspector or Component inspector during authoring. Using the DateChooser component (Flash Professional only) The DateChooser can be used anywhere you want a user to select a date. For example, you could use a DateChooser component in a hotel reservation system with certain dates selectable and others disabled. You could also use the DateChooser component in an application that displays current events, such as performances or meetings, when a user chooses a date. DateChooser parameters You can set the following authoring parameters for each DateChooser component instance in the Property inspector or in the Component inspector: monthNames sets the month names that are displayed in the heading row of the calendar. The value is an array and the default value is ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"]. dayNames
sets the names of the days of the week. The value is an array and the default value is
["S", "M", "T", "W", "T", "F", "S"]. firstDayOfWeek indicates which day of the week (0-6, 0 being the first element of the dayNames
array) is displayed in the first column of the date chooser. This property changes the display order of the day columns. disabledDays indicates the disabled days of the week. This parameter is an array and can have up
to seven values. The default value is [] (an empty array). showToday
indicates whether to highlight today’s date. The default value is true.
You can write ActionScript to control these and additional options for the DateChooser component using its properties, methods, and events. For more information, see “DateChooser class (Flash Professional only)” on page 354. Creating an application with the DateChooser component The following procedure explains how to add a DateChooser component to an application while authoring. In this example, the date chooser allows a user to pick a date for an airline reservation system. All dates before October 15th must be disabled. Also, a range in December must be disabled to create a holiday black-out period, and Mondays must be disabled.
350
Chapter 6: Components Dictionary
To create an application with the DateChooser component:
1. Double-click the DateChooser component in the Components panel to add it to the Stage. 2. In the Property inspector, enter the instance name flightCalendar. 3. In the Actions panel, enter the following code on Frame 1 of the Timeline to set the range of
This code assigns a value to the selectableRange property in an ActionScript object that contains two Date objects with the variable names rangeStart and rangeEnd. This defines an upper and lower end of a range in which the user can select a date. 4. In the Actions panel, enter the following code on Frame 1 of the Timeline to set a range of
holiday disabled dates: flightCalendar.disabledRanges = [{rangeStart: new Date(2003, 11, 15), rangeEnd: new Date(2003, 11, 26)}];
5. In the Actions panel, enter the following code on Frame 1 of the Timeline to disable Mondays: flightCalendar.disabledDays=[1];
6. Select Control > Test Movie.
Customizing the DateChooser component (Flash Professional only) You can transform a DateChooser component horizontally and vertically while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()). Using styles with the DateChooser component You can set style properties to change the appearance of a DateChooser instance. If the name of a style property ends in “Color”, it is a color style property and behaves differently than noncolor style properties. For more information, see “Using styles to customize component color and text” on page 67. A DateChooser component supports the following styles: Style
Theme Description
themeColor
Halo
The glow color for the rollover and selected dates. Possible values are "haloGreen", "haloBlue", and "haloOrange". The default value is "haloGreen".
backgroundColor
Both
The background color. The default value is 0xEFEBEF (light gray).
borderColor
Both
The border color. The default value is 0x919999. The DateChooser component uses a solid single-pixel line as its border. This border cannot be modified through styles or skinning.
DateChooser component (Flash Professional only)
351
Style
Theme Description
headerColor
Both
The background color for the component heading. The default color is white.
rollOverColor
Both
The background color of a rolled-over date. The default value is 0xE3FFD6 (bright green) with the Halo theme and 0xAAAAAA (light gray) with the Sample theme.
selectionColor
Both
The background color of the selected date. The default value is 0xCDFFC1 (light green) with the Halo theme and 0xEEEEEE (very light gray) with the Sample theme.
todayColor
Both
The background color for the today’s date. The default value is 0x666666 (dark gray).
color
Both
The text color. The default value is 0x0B333C with the Halo theme and blank with the Sample theme.
disabledColor
Both
The color for text when the component is disabled. The default color is 0x848384 (dark gray).
embedFonts
Both
A Boolean value that indicates whether the font specified in fontFamily is an embedded font. This style must be set to true if fontFamily refers to an embedded font. Otherwise, the embedded font will not be used. If this style is set to true and fontFamily does not refer to an embedded font, no text will be displayed. The default value is false.
fontFamily
Both
The font name for text. The default value is "_sans".
fontSize
Both
The point size for the font. The default value is 10.
fontStyle
Both
The font style: either "normal" or "italic". The default value is "normal".
fontWeight
Both
The font weight: either "none" or "bold". The default value is "none". All components can also accept the value "normal" in place of "none" during a setStyle() call, but subsequent calls to getStyle() will return "none".
textDecoration
Both
The text decoration: either "none" or "underline". The default value is "none".
The DateChooser component uses four categories of text to display the month name, the days of the week, today’s date, and regular dates. The text style properties set on the DateChooser component itself control the regular date text and provide defaults for the other text. To set text styles for specific categories of text, use the following class-level style declarations.
352
Declaration name
Description
HeaderDateText
The month name.
WeekDayStyle
The days of the week.
TodayStyle
Today’s date.
Chapter 6: Components Dictionary
The following example demonstrates how to set the month name and days of the week to a deep red color. _global.styles.HeaderDateText.setStyle("color", 0x660000); _global.styles.WeekDayStyle.setStyle("color", 0x660000);
Using skins with the DateChooser component The DateChooser component uses skins to represent the forward and back month buttons and the today indicator. To skin the DateChooser component while authoring, modify skin symbols in the Flash UI Components 2/Themes/MMDefault/DateChooser Assets/States folder in the library of one of the themes FLA files. For more information, see “About skinning components” on page 80. Only the month scrolling buttons can be dynamically skinned in this component. A DateChooser component uses the following skin properties: Property
Description
backMonthButtonUpSymbolName
The month back button up state. The default value is backMonthUp.
backMonthButtonDownSymbolName
The month back button pressed state. The default value is backMonthDown.
backMonthButtonDisabledSymbolName
The month back button disabled state. The default value is backMonthDisabled.
fwdMonthButtonUpSymbolName
The month forward button up state. The default value is fwdMonthUp.
fwdMonthButtonDownSymbolName
The month forward button pressed state. The default value is fwdMonthDown.
fwdMonthButtonDisabledSymbolName
The month forward button disabled state. The default value is fwdMonthDisabled.
The button symbols are used exactly as is without applying colors or resizing. The size is determined by the symbol during authoring. To create movie clip symbols for DateChooser skins:
1. Create a new FLA file. 2. Select File > Import > Open External Library, and select the HaloTheme.fla file.
This file is located in the application-level configuration folder. For the exact location on your operating system, see “About themes” on page 77. 3. In the theme’s Library panel, expand the Flash UI Components 2/Themes/MMDefault folder
and drag the DateChooser Assets folder to the library for your document. 4. Expand the DateChooser Assets/States folder in the library of your document. 5. Open the symbols you want to customize for editing.
For example, open the backMonthDown symbol.
DateChooser component (Flash Professional only)
353
6. Customize the symbol as desired.
For example, change the tint of the arrow to red. 7. Repeat steps 5-6 for all symbols you want to customize.
For example, change the tint of the forward arrow down symbol to match the back arrow. 8. Click the Back button to return to the main Timeline. 9. Drag a DateChooser component to the Stage. 10. Select Control > Test Movie. Note: The DateChooser Assets/States folder also has a Day Skins folder with a single skin element, cal_todayIndicator. This element can be modified during authoring to customize the today indicator. However, it cannot be changed dynamically on a particular DateChooser instance to use a different symbol. In addition, the cal_todayIndicator symbol must be a solid single-color graphic, because the DateChooser component will apply the todayColor color to the graphic as a whole. The graphic may have cut-outs, but keep in mind that the default text color for today’s date is white and the default background for the DateChooser is white, so a cut-out in the middle of the today indicator skin element would make today’s date unreadable unless either the background color or today text color is also changed.
DateChooser class (Flash Professional only) Inheritance
MovieClip > UIObject class > UIComponent class > DateChooser
ActionScript Class Name
mx.controls.DateChooser
The properties of the DateChooser class let you access the selected date and the displayed month and year. You can also set the names of the days and months, indicate disabled dates and selectable dates, set the first day of the week, and indicate whether the current date should be highlighted. Setting a property of the DateChooser class with ActionScript overrides the parameter of the same name set in the Property inspector or Component inspector. Each component class has a version property, which is a class property. Class properties are available only on the class itself. The version property returns a string that indicates the version of the component. To access this property, use the following code: trace(mx.controls.DateChooser.version); Note: The code trace(myDC.version); returns undefined.
Method summary for the DateChooser class There are no methods exclusive to the DateChooser class.
354
Chapter 6: Components Dictionary
Methods inherited from the UIObject class
The following table lists the methods the DateChooser class inherits from the UIObject class. When calling these methods from the DateChooser object, use the form dateChooserInstance.methodName. Method
Description
UIObject.createClassObject() Creates an object on the specified class. UIObject.createObject()
Creates a subobject on an object.
UIObject.destroyObject()
Destroys a component instance.
UIObject.doLater()
Calls a function when parameters have been set in the Property and Component inspectors.
UIObject.getStyle()
Gets the style property from the style declaration or object.
UIObject.invalidate()
Marks the object so it will be redrawn on the next frame interval.
UIObject.move()
Moves the object to the requested position.
UIObject.redraw()
Forces validation of the object so it is drawn in the current frame.
UIObject.setSize()
Resizes the object to the requested size.
UIObject.setSkin()
Sets a skin in the object.
UIObject.setStyle()
Sets the style property on the style declaration or object.
Methods inherited from the UIComponent class
The following table lists the methods the DateChooser class inherits from the UIComponent class. When calling these methods from the DateChooser object, use the form dateChooserInstance.methodName. Method
Description
UIComponent.getFocus()
Returns a reference to the object that has focus.
UIComponent.setFocus()
Sets focus to the component instance.
Property summary for the DateChooser class The following table lists the properties that are exclusive to the DateChooser class. Property
Description
DateChooser.dayNames
An array indicating the names of the days of the week.
DateChooser.disabledDays
An array indicating the days of the week that are disabled for all applicable dates in the date chooser.
DateChooser.disabledRanges
A range of disabled dates or a single disabled date.
DateChooser.displayedMonth
A number indicating an element in the monthNames array to display in the date chooser.
DateChooser.displayedYear
A number indicating the year to display.
DateChooser component (Flash Professional only)
355
Property
Description
DateChooser.firstDayOfWeek
A number indicating an element in the dayNames array to display in the first column of the date chooser.
DateChooser.monthNames
An array of strings indicating the month names.
DateChooser.selectableRange A single selectable date or a range of selectable dates. DateChooser.selectedDate
A Date object indicating the selected date.
DateChooser.showToday
A Boolean value indicating whether the current date is highlighted.
Properties inherited from the UIObject class
The following table lists the properties the DateChooser class inherits from the UIObject class. When accessing these properties from the DateChooser object, use the form dateChooserInstance.propertyName. Property
Description
UIObject.bottom
The position of the bottom edge of the object, relative to the bottom edge of its parent. Read-only.
UIObject.height
The height of the object, in pixels. Read-only.
UIObject.left
The left edge of the object, in pixels. Read-only.
UIObject.right
The position of the right edge of the object, relative to the right edge of its parent. Read-only.
UIObject.scaleX
A number indicating the scaling factor in the x direction of the object, relative to its parent.
UIObject.scaleY
A number indicating the scaling factor in the y direction of the object, relative to its parent.
UIObject.top
The position of the top edge of the object, relative to its parent. Read-only.
UIObject.visible
A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width
The width of the object, in pixels. Read-only.
UIObject.x
The left edge of the object, in pixels. Read-only.
UIObject.y
The top edge of the object, in pixels. Read-only.
Properties inherited from the UIComponent class
The following table lists the properties the DateChooser class inherits from the UIComponent class. When accessing these properties from the DateChooser object, use the form dateChooserInstance.propertyName.
356
Property
Description
UIComponent.enabled
Indicates whether the component can receive focus and input.
UIComponent.tabIndex
A number indicating the tab order for a component in a document.
Chapter 6: Components Dictionary
Event summary for the DateChooser class The following table lists the events that are exclusive to the DateChooser class. Event
Description
DateChooser.change
Broadcast when a date is selected.
DateChooser.scroll
Broadcast when the month buttons are clicked.
Events inherited from the UIObject class
The following table lists the events the DateChooser class inherits from the UIObject class. Event
Description
UIObject.draw
Broadcast when an object is about to draw its graphics.
UIObject.hide
Broadcast when an object’s state changes from visible to invisible.
UIObject.load
Broadcast when subobjects are being created.
UIObject.move
Broadcast when the object has moved.
UIObject.resize
Broadcast when an object has been resized.
UIObject.reveal
Broadcast when an object’s state changes from invisible to visible.
UIObject.unload
Broadcast when the subobjects are being unloaded.
Events inherited from the UIComponent class
The following table lists the events the DateChooser class inherits from the UIComponent class. Event
Event; broadcast to all registered listeners when a date is selected. The first usage example uses an on() handler and must be attached directly to a DateChooser instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date chooser myDC, sends “_level0.myDC” to the Output panel: on(change){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (chooserInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. Finally, you call the EventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
This example, written on a frame of the Timeline, sends a message to the Output panel when a DateChooser instance called myDC is changed. The first line of code creates a listener object called form. The second line defines a function for the change event on the listener object. Inside the function is a trace() statement that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event (in this example, myDC). The NumericStepper.maximum property is accessed from the event object’s target property. The last line calls EventDispatcher.addEventListener() from myDC and passes it the change event and the form listener object as parameters. form.change = function(eventObj){ trace("date selected " + eventObj.target.selectedDate); } myDC.addEventListener("change", form);
358
Chapter 6: Components Dictionary
DateChooser.dayNames Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.dayNames Description
Property; an array containing the names of the days of the week. Sunday is the first day (at index position 0) and the rest of the day names follow in order. The default value is ["S", "M", "T", "W", "T", "F", "S"]. Example
The following example changes the value of the fifth day of the week (Thursday) from “T” to “R”: myDC.dayNames[4] = "R";
DateChooser.disabledDays Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.disabledDays Description
Property; an array indicating the disabled days of the week. All the dates in a month that fall on the specified day are disabled. The elements of this array can have values from 0 (Sunday) to 6 (Saturday). The default value is [] (an empty array). Example
The following example disables Sundays and Saturdays so that users can select only weekdays: myDC.disabledDays = [0, 6];
DateChooser component (Flash Professional only)
359
DateChooser.disabledRanges Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.disabledRanges Description
Property; disables a single day or a range of days. This property is an array of objects. Each object in the array must be either a Date object that specifies a single day to disable, or an object that contains either or both of the properties rangeStart and rangeEnd, each of whose value must be a Date object. The rangeStart and rangeEnd properties describe the boundaries of the date range. If either property is omitted, the range is unbounded in that direction. The default value of disabledRanges is undefined. Specify a full date when you define dates for the disabledRanges property. For example, specify rather than new Date(). If you don’t specify a full date, the time returns as 00:00:00. new Date(2003,6,24)
Example
The following example defines an array with rangeStart and rangeEnd Date objects that disable the dates between May 7 and June 7: myDC.disabledRanges = [{rangeStart: new Date(2003, 4, 7), rangeEnd: new Date(2003, 5, 7)}];
The following example disables all dates after November 7: myDC.disabledRanges = [ {rangeStart: new Date(2003, 10, 7)} ];
The following example disables all dates before October 7: myDC.disabledRanges = [ {rangeEnd: new Date(2002, 9, 7)} ];
The following example disables only December 7: myDC.disabledRanges = [ new Date(2003, 11, 7) ];
DateChooser.displayedMonth Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.displayedMonth
360
Chapter 6: Components Dictionary
Description
Property; a number indicating which month is displayed. The number indicates an element in the monthNames array, with 0 being the first month. The default value is the month of the current date. Example
The following example sets the displayed month to December: myDC.displayedMonth = 11; See also DateChooser.displayedYear
DateChooser.displayedYear Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.displayedYear Description
Property; a four-digit number indicating which year is displayed. The default value is the current year. Example
The following example sets the displayed year to 2010: myDC.displayedYear = 2010; See also DateChooser.displayedMonth
DateChooser.firstDayOfWeek Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.firstDayOfWeek
DateChooser component (Flash Professional only)
361
Description
Property; a number indicating which day of the week (0-6, 0 being the first element of the dayNames array) is displayed in the first column of the DateChooser component. Changing this property changes the order of the day columns but has no effect on the order of the dayNames property. The default value is 0 (Sunday). Example
The following example sets the first day of the week to Monday: myDC.firstDayOfWeek = 1; See also DateChooser.dayNames
DateChooser.monthNames Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.monthNames Description
Property; an array of strings indicating the month names at the top of the DateChooser component. The default value is ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]. Example
The following example sets the month names for the instance myDC: myDC.monthNames = ["Jan", "Feb","Mar","Apr", "May", "June","July", "Aug", "Sept","Oct", "Nov", "Dec"];
Event; broadcast to all registered listeners when a month button is clicked. The first usage example uses an on() handler and must be attached directly to a DateChooser instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date chooser myDC, sends “_level0.myDC” to the Output panel: on(scroll){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (myDC) dispatches an event (in this case, scroll) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The scroll event’s event object has an additional property, detail, that can have one of the following values: nextMonth, previousMonth, nextYear, previousYear. Finally, you call the EventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
This example, written on a frame of the Timeline, sends a message to the Output panel when a month button is clicked on a DateChooser instance called myDC. The first line of code creates a listener object called form. The second line defines a function for the scroll event on the listener object. Inside the function is a trace() statement that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event—in this example, myDC. The last line calls EventDispatcher.addEventListener() from myDC and passes it the scroll event and the form listener object as parameters. form = new Object(); form.scroll = function(eventObj){ trace(eventObj.detail);
DateChooser component (Flash Professional only)
363
} myDC.addEventListener("scroll", form);
DateChooser.selectableRange Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.selectableRange Description
Property; sets a single selectable date or a range of selectable dates. The user cannot scroll beyond the selectable range. The value of this property is an object that consists of two Date objects named rangeStart and rangeEnd. The rangeStart and rangeEnd properties designate the boundaries of the selectable date range. If only rangeStart is defined, all the dates after rangeStart are enabled. If only rangeEnd is defined, all the dates before rangeEnd are enabled. The default value is undefined. If you want to enable only a single day, you can use a single Date object as the value of selectableRange. Specify a full date when you define dates—for example, new Date(2003,6,24) rather than new Date(). If you don’t specify a full date, the time returns as 00:00:00. The value of DateChooser.selectedDate is set to undefined if it falls outside the selectable range. The values of DateChooser.displayedMonth and DateChooser.displayedYear are set to the the nearest last month in the selectable range if the current month falls outside the selectable range. For example, if the current displayed month is August, and the selectable range is from June 2003 to July,2003, the displayed month will change to July 2003. Example
The following example defines the selectable range as the dates between and including May 7 and June 7: myDC.selectableRange = {rangeStart: new Date(2001, 4, 7), rangeEnd: new Date(2003, 5, 7)};
The following example defines the selectable range as the dates after and including May 7: myDC.selectableRange = {rangeStart: new Date(2003, 4, 7)};
The following example defines the selectable range as the dates before and including June 7: myDC.selectableRange = {rangeEnd: new Date(2003, 5, 7)};
The following example defines the selectable date as June 7 only: myDC.selectableRange = new Date(2003, 5, 7);
364
Chapter 6: Components Dictionary
DateChooser.selectedDate Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.selectedDate Description
Property; a Date object that indicates the selected date if that value falls within the value of the selectableRange property. The default value is undefined. You cannot set the selectedDate property within a disabled range, outside a selectable range, or on a day that has been disabled. If this property is set to one of these dates, the value is undefined. Example
The following example sets the selected date to June 7: myDC.selectedDate = new Date(2003, 5, 7);
DateChooser.showToday Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDC.showToday Description
Property; a Boolean value that determines whether the current date is highlighted. The default value is true. Example
The following example turns off the highlighting on today’s date: myDC.showToday = false;
DateChooser component (Flash Professional only)
365
CHAPTER 6 Components Dictionary
DateField component (Flash Professional only)
The DateField component is a nonselectable text field that displays the date with a calendar icon on its right side. If no date has been selected, the text field is blank and the month of today’s date is displayed in the date chooser. When a user clicks anywhere inside the bounding box of the date field, a date chooser pops up and displays the dates in the month of the selected date. When the date chooser is open, users can use the month scroll buttons to scroll through months and years and select a date. When a date is selected, the date chooser closes. The live preview of the DateField does not reflect the values indicated by the Property inspector or Component inspector during authoring, because it is a pop-up component that is not visible during authoring. Using the DateField component (Flash Professional only) The DateField component can be used anywhere you want a user to select a date. For example, you could use a DateField component in a hotel reservation system with certain dates selectable and others disabled. You could also use the DateField component in an application that displays current events, such as performances or meetings, when a user chooses a date. DateField parameters You can set the following authoring parameters for each DateField component instance in the Property inspector or in the Component inspector: monthNames sets the month names that are displayed in the heading row of the calendar. The value is an array and the default value is ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"]. dayNames
sets the names of the days of the week. The value is an array and the default value is
["S", "M", "T", "W", "T", "F", "S"]. firstDayOfWeek indicates which day of the week (0-6, 0 being the first element of dayNames array) is displayed in the first column of the date chooser. This property changes the display order of the day columns.
The default value is 0, which is "S". disabledDays indicates the disabled days of the week. This parameter is an array and can have up
to seven values. The default value is [] (an empty array). showToday
indicates whether to highlight today’s date. The default value is true.
You can write ActionScript to control these and additional options for the DateField component using its properties, methods, and events. For more information, see “DateField class (Flash Professional only)” on page 371.
DateField component (Flash Professional only)
367
Creating an application with the DateField component The following procedure explains how to add a DateField component to an application while authoring. In this example, the DateField component allows a user to pick a date for an airline reservation system. All dates before today’s date must be disabled. Also, a 15-day range in December must be disabled to create a holiday black-out period. Also, some flights are not available on Mondays, so all Mondays must be disabled for those flights. To create an application with the DateField component:
1. Double-click the DateField component in the Components panel to add it to the Stage. 2. In the Property inspector, enter the instance name flightCalendar. 3. In the Actions panel, enter the following code on Frame 1 of the Timeline to set the range of
This code assigns a value to the selectableRange property in an ActionScript object that contains two Date objects with the variable names rangeStart and rangeEnd. This defines an upper and lower end of a range within which the user can select a date. 4. In the Actions panel, enter the following code on Frame 1 of the Timeline to set the ranges of
disabled dates, one during December, and one for all dates before the current date: flightCalendar.disabledRanges = [{rangeStart: new Date(2003, 11, 15), rangeEnd: new Date(2003, 11, 31)}, {rangeEnd: new Date(2003, 6, 16)}];
5. In the Actions panel, enter the following code on Frame 1 of the Timeline to disable Mondays: flightCalendar.disabledDays=[1];
6. Control > Test Movie.
Customizing the DateField component (Flash Professional only) You can transform a DateField component horizontally while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()). Setting the width does not change the dimensions of the date chooser in the DateField component. However, you can use the pullDown property to access the DateChooser component and set its dimensions. Using styles with the DateField component You can set style properties to change the appearance of a date field instance. If the name of a style property ends in “Color”, it is a color style property and behaves differently than noncolor style properties. For more information, see “Using styles to customize component color and text” on page 67.
368
Chapter 6: Components Dictionary
The DateField component supports the following styles: Style
Theme Description
themeColor
Halo
The glow color for the rollover and selected dates. Possible values are "haloGreen", "haloBlue", and "haloOrange". The default value is "haloGreen"
backgroundColor
Both
The background color. The default value is 0xEFEBEF (light gray).
borderColor
Both
The border color. The default value is 0x919999. The DateField component’s drop-down list uses a solid single-pixel line as its border. This border cannot be modified through styles or skinning.
headerColor
Both
The background color for the drop-down heading. The default color is white.
rollOverColor
Both
The background color of a rolled-over date. The default value is 0xE3FFD6 (bright green) with the Halo theme and 0xAAAAAA (light gray) with the Sample theme.
selectionColor
Both
The background color of the selected date. The default value is a 0xCDFFC1 (light green) with the Halo theme and 0xEEEEEE (very light gray) with the Sample theme.
todayColor
Both
The background color for the today’s date. The default value is 0x666666 (dark gray).
color
Both
The text color. The default value is 0x0B333C with the Halo theme and blank with the Sample theme.
disabledColor
Both
The color for text when the component is disabled. The default color is 0x848384 (dark gray).
embedFonts
Both
A Boolean value that indicates whether the font specified in fontFamily is an embedded font. This style must be set to true if fontFamily refers to an embedded font. Otherwise, the embedded font will not be used. If this style is set to true and fontFamily does not refer to an embedded font, no text will be displayed. The default value is false.
fontFamily
Both
The font name for text. The default value is "_sans".
fontSize
Both
The point size for the font. The default value is 10.
fontStyle
Both
The font style: either "normal" or "italic". The default value is "normal".
fontWeight
Both
The font weight: either "none" or "bold". The default value is "none". All components can also accept the value "normal" in place of "none" during a setStyle() call, but subsequent calls to getStyle() will return "none".
textDecoration
Both
The text decoration: either "none" or "underline". The default value is "none".
DateField component (Flash Professional only)
369
The DateField component uses four categories of text to display the month name, the days of the week, today’s date, and regular dates. The text style properties set on the DateField component itself control the regular date text and the text displayed in the collapsed state, and provide defaults for the other text. To set text styles for specific categories of text, use the following classlevel style declarations. Declaration name
Description
HeaderDateText
The month name.
WeekDayStyle
The days of the week.
TodayStyle
Today’s date.
The following example demonstrates how to set the month name and days of the week to a deep red color. _global.styles.HeaderDateText.setStyle("color", 0x660000); _global.styles.WeekDayStyle.setStyle("color", 0x660000);
Using skins with the DateField component The DateField component uses skins to represent the visual states of the pop-up icon, a RectBorder instance for the border around the text input, and a DateChooser instance for the pop-up. To skin the pop-up icon while authoring, modify skin symbols in the Flash UI Components 2/Themes/MMDefault/DateField Assets/States folder in the library of one of the themes FLA files. For more information, see “About skinning components” on page 80. For information about skinning the RectBorder and DateChooser instances, see “RectBorder class” on page 647 and “Using skins with the DateChooser component” on page 353. Besides the skins used by the subcomponents mentioned above, a DateField component uses the following skin properties to dynamically skin the pop-up icon: Property
Description
openDateUp
The up state of the pop-up icon.
openDateDown
The down state of the pop-up icon.
openDateOver
The over state of the pop-up icon.
openDateDisabled
The disabled state of the pop-up icon.
To create movie clip symbols for DateField skins:
1. Create a new FLA file. 2. Select File > Import > Open External Library, and select the HaloTheme.fla file.
This file is located in the application-level configuration folder. For the exact location on your operating system, see “About themes” on page 77. 3. In the theme’s Library panel, expand the Flash UI Components 2/Themes/MMDefault folder
and drag the DateField Assets folder to the library for your document. 4. Expand the DateField Assets folder in the library of your document.
370
Chapter 6: Components Dictionary
5. Ensure that the DateFieldAssets symbol is selected for Export in First Frame. 6. Expand the DateField Assets/States folder in the library of your document. 7. Open the symbols you want to customize for editing.
For example, open the openIconUp symbol. 8. Customize the symbol as desired.
For example, draw a down arrow over the calendar image. 9. Repeat steps 7-8 for all symbols you want to customize.
For example, draw a down arrow over all of the symbols. 10. Click the Back button to return to the main Timeline. 11. Drag a DateField component to the Stage. 12. Select Control > Test Movie.
DateField class (Flash Professional only) Inheritance
MovieClip > UIObject class > UIComponent class > ComboBase > DateField
ActionScript Class Name
mx.controls.DateField
The properties of the DateField class let you access the selected date and the displayed month and year. You can also set the names of the days and months, indicate disabled dates and selectable dates, set the first day of the week, and indicate whether the current date should be highlighted. Setting a property of the DateField class with ActionScript overrides the parameter of the same name set in the Property inspector or Component inspector. Each component class has a version property, which is a class property. Class properties are available only on the class itself. The version property returns a string that indicates the version of the component. To access this property, use the following code: trace(mx.controls.DateField.version); Note: The code trace(myDateFieldInstance.version); returns undefined.
Method summary for the DateField class The following table lists methods of the DateField class. Method
Description
DateField.close()
Closes the pop-up DateChooser subcomponent.
DateField.open()
Opens the pop-up DateChooser subcomponent.
DateField component (Flash Professional only)
371
Methods inherited from the UIObject class
The following table lists the methods the DateField class inherits from the UIObject class. When calling these methods from the DateField object, use the form dateFieldInstance.methodName. Method
Description
UIObject.createClassObject() Creates an object on the specified class. UIObject.createObject()
Creates a subobject on an object.
UIObject.destroyObject()
Destroys a component instance.
UIObject.doLater()
Calls a function when parameters have been set in the Property and Component inspectors.
UIObject.getStyle()
Gets the style property from the style declaration or object.
UIObject.invalidate()
Marks the object so it will be redrawn on the next frame interval.
UIObject.move()
Moves the object to the requested position.
UIObject.redraw()
Forces validation of the object so it is drawn in the current frame.
UIObject.setSize()
Resizes the object to the requested size.
UIObject.setSkin()
Sets a skin in the object.
UIObject.setStyle()
Sets the style property on the style declaration or object.
Methods inherited from the UIComponent class
The following table lists the methods the DateField class inherits from the UIComponent class. When calling these methods from the DateField object, use the form dateFieldInstance.methodName. Method
Description
UIComponent.getFocus()
Returns a reference to the object that has focus.
UIComponent.setFocus()
Sets focus to the component instance.
Property summary for the DateField class The following table lists properties of the DateField class.
372
Property
Description
DateField.dateFormatter
A function that formats the date to be displayed in the text field.
DateField.dayNames
An array indicating the names of the days of the week.
DateField.disabledDays
An array indicating the disabled days of the week.
DateField.disabledRanges
A range of disabled dates or a single disabled date.
DateField.displayedMonth
A number indicating which element in the monthNames array to display.
DateField.displayedYear
A number indicating the year to display.
Chapter 6: Components Dictionary
Property
Description
DateField.firstDayOfWeek
A number indicating an element in the dayNames array to display in the first column of the DateField component.
DateField.monthNames
An array of strings indicating the month names.
DateField.pullDown
A reference to the DateChooser subcomponent. This property is read-only.
DateField.selectableRange
A single selectable date or a range of selectable dates.
DateField.selectedDate
A Date object indicating the selected date.
DateField.showToday
A Boolean value indicating whether the current date is highlighted.
Properties inherited from the UIObject class
The following table lists the properties the DateField class inherits from the UIObject class. When accessing these properties from the DateField object, use the form dateFieldInstance.propertyName. Property
Description
UIObject.bottom
The position of the bottom edge of the object, relative to the bottom edge of its parent. Read-only.
UIObject.height
The height of the object, in pixels. Read-only.
UIObject.left
The left edge of the object, in pixels. Read-only.
UIObject.right
The position of the right edge of the object, relative to the right edge of its parent. Read-only.
UIObject.scaleX
A number indicating the scaling factor in the x direction of the object, relative to its parent.
UIObject.scaleY
A number indicating the scaling factor in the y direction of the object, relative to its parent.
UIObject.top
The position of the top edge of the object, relative to its parent. Read-only.
UIObject.visible
A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width
The width of the object, in pixels. Read-only.
UIObject.x
The left edge of the object, in pixels. Read-only.
UIObject.y
The top edge of the object, in pixels. Read-only.
DateField component (Flash Professional only)
373
Properties inherited from the UIComponent class
The following table lists the properties the DateField class inherits from the UIComponent class. When accessing these properties from the DateField object, use the form dateFieldInstance.propertyName. Property
Description
UIComponent.enabled
Indicates whether the component can receive focus and input.
UIComponent.tabIndex
A number indicating the tab order for a component in a document.
Event summary for the DateField class The following table lists events of the DateField class. Event
Description
DateField.change
Broadcast when a date is selected.
DateField.close
Broadcast when the DateChooser subcomponent closes.
DateField.open
Broadcast when the DateChooser subcomponent opens.
DateField.scroll
Broadcast when the month buttons are clicked.
Events inherited from the UIObject class
The following table lists the events the DateField class inherits from the UIObject class. Event
Description
UIObject.draw
Broadcast when an object is about to draw its graphics.
UIObject.hide
Broadcast when an object’s state changes from visible to invisible.
UIObject.load
Broadcast when subobjects are being created.
UIObject.move
Broadcast when the object has moved.
UIObject.resize
Broadcast when an object has been resized.
UIObject.reveal
Broadcast when an object’s state changes from invisible to visible.
UIObject.unload
Broadcast when the subobjects are being unloaded.
Events inherited from the UIComponent class
The following table lists the events the DateField class inherits from the UIComponent class.
Event; broadcast to all registered listeners when a date is selected. The first usage example uses an on() handler and must be attached directly to a DateField instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date field myDF, sends “_level0.myDF” to the Output panel: on(change){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (myDF) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. Finally, you call the EventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415.
DateField component (Flash Professional only)
375
Example
This example, written on a frame of the Timeline, sends a message to the Output panel when a date field called myDF is changed. The first line of code creates a listener object called form. The second line defines a function for the change event on the listener object. Inside the function is a trace() statement that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event—in this example, myDF. The DateField.selectedDate property is accessed from the event object’s target property. The last line calls EventDispatcher.addEventListener() from myDF and passes it the change event and the form listener object as parameters. function change(eventObj){ trace("date selected " + eventObj.target.selectedDate) ; } myDF.addEventListener("change", this);
DateField.close() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.close() Parameters
None. Returns
Nothing. Description
Method; closes the pop-up menu. Example
The following code closes the date chooser pop-up of the myDF date field instance: myDF.close();
Event; broadcast to all registered listeners when the DateChooser subcomponent closes after a user clicks outside the icon or selects a date. The first usage example uses an on() handler and must be attached directly to a DateField instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date field myDF, sends “_level0.myDF” to the Output panel: on(close){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (myDF) dispatches an event (in this case, close) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. Finally, you call the EventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
This example, written on a frame of the Timeline, sends a message to the Output panel when the date chooser in myDF closes. The first line of code creates a listener object called form. The second line defines a function for the close event on the listener object. Inside the function is a trace() statement that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event—in this example, myDF. The property is accessed from the event object’s target property. The last line calls EventDispatcher.addEventListener() from myDF and passes it the close event and the form listener object as parameters.
Flash MX Professional 2004. Usage myDF.dateFormatter Description
Property; a function that formats the date to be displayed in the text field. The function must receive a Date object as parameter, and return a string in the format to be displayed. Example
The following example sets the function to return the format of the date to be displayed: myDF.dateFormatter = function(d:Date){ return d.getFullYear()+"/ "+(d.getMonth()+1)+"/ "+d.getDate(); };
DateField.dayNames Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.dayNames Description
Property; an array containing the names of the days of the week. Sunday is the first day (at index position 0) and the other day names follow in order. The default value is ["S", "M", "T", "W", "T", "F", "S"]. Example
The following example changes the value of the fifth day of the week (Thursday) from “T” to “R”: myDF.dayNames[4] = "R";
378
Chapter 6: Components Dictionary
DateField.disabledDays Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.disabledDays Description
Property; an array indicating the disabled days of the week. All the dates in a month that fall on the specified day are disabled. The elements of this array can have values between 0 (Sunday) and 6 (Saturday). The default value is [] (an empty array). Example
The following example disables Sundays and Saturdays so that users can select only weekdays: myDF.disabledDays = [0, 6];
DateField.disabledRanges Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.disabledRanges Description
Property; disables a single day or a range of days. This property is an array of objects. Each object in the array must be either a Date object specifying a single day to disable, or an object containing either or both of the properties rangeStart and rangeEnd, each of whose value must be a Date object. The rangeStart and rangeEnd properties describe the boundaries of the date range. If either property is omitted, the range is unbounded in that direction. The default value of disabledRanges is undefined. Specify a full date when you define dates for the disabledRanges property—for example, new rather than new Date(). If you don’t specify a full date, the time returns as 00:00:00.
Date(2003,6,24)
DateField component (Flash Professional only)
379
Example
The following example defines an array with rangeStart and rangeEnd Date objects that disable the dates between May 7 and June 7: myDF.disabledRanges = [ {rangeStart: new Date(2003, 4, 7), rangeEnd: new Date(2003, 5, 7)}];
The following example disables all dates after November 7: myDF.disabledRanges = [ {rangeStart: new Date(2003, 10, 7)} ];
The following example disables all dates before October 7: myDF.disabledRanges = [ {rangeEnd: new Date(2002, 9, 7)} ];
The following example disables only December 7: myDF.disabledRanges = [ new Date(2003, 11, 7) ];
DateField.displayedMonth Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.displayedMonth Description
Property; a number indicating which month is displayed. The number indicates an element in the monthNames array, with 0 being the first month. The default value is the month of the current date. Example
The following example sets the displayed month to December: myDF.displayedMonth = 11; See also DateField.displayedYear
DateField.displayedYear Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004.
380
Chapter 6: Components Dictionary
Usage myDF.displayedYear Description
Property; a number indicating which year is displayed. The default value is the current year. Example
The following example sets the displayed year to 2010: myDF.displayedYear = 2010; See also DateField.displayedMonth
DateField.firstDayOfWeek Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.firstDayOfWeek Description
Property; a number indicating which day of the week (0-6, 0 being the first element of the dayNames array) is displayed in the first column of the DateField component. Changing this property changes the order of the day columns but has no effect on the order of the dayNames property. The default value is 0 (Sunday). Example
The following example sets the first day of the week to Monday: myDF.firstDayOfWeek = 1; See also DateField.dayNames
DateField.monthNames Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.monthNames
DateField component (Flash Professional only)
381
Description
Property; an array of strings indicating the month names at the top of the DateField component. The default value is ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]. Example
The following example sets the month names for the instance myDF: myDF.monthNames = ["Jan", "Feb","Mar","Apr", "May", "June","July", "Aug", "Sept","Oct", "Nov", "Dec"];
DateField.open() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.open() Parameters
None. Returns
Nothing. Description
Method; opens the pop-up DateChooser subcomponent. Example
The following code opens the pop-up date chooser of the df instance: df.open();
Event; broadcast to all registered listeners when a DateChooser subcomponent opens after a user clicks on the icon. The first usage example uses an on() handler and must be attached directly to a DateField instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date field myDF, sends “_level0.myDF” to the Output panel: on(open){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (myDF) dispatches an event (in this case, open) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. Finally, you call the EventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
This example, written on a frame of the Timeline, sends a message to the Output panel when a date field called myDF is opened. The first line of code creates a listener object called form. The second line defines a function for the open event on the listener object. Inside the function is a trace() statement that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event—in this example, myDF. The DateField.selectedDate property is accessed from the event object’s target property. The last line calls EventDispatcher.addEventListener() from myDF and passes it the open event and the form listener object as parameters. form.open = function(eventObj){ trace("Pop-up opened and date selected is " + eventObj.target.selectedDate) ;
DateField component (Flash Professional only)
383
} myDF.addEventListener("open", form);
DateField.pullDown Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.pullDown Description
Property (read-only); a reference to the DateChooser component contained by the DateField component. The DateChooser subcomponent is instantiated when a user clicks on the DateField component. However, if the pullDown property is referenced before the user clicks on the component, the DateChooser is instantiated and then hidden. Example
The following example sets the visibility of the DateChooser subcomponent to false and then sets the size of the DateChooser subcomponent to 300 pixels high and 300 pixels wide: myDF.pullDown._visible = false; myDF.pullDown.setSize(300,300);
Event; broadcast to all registered listeners when a month button is clicked. The first usage example uses an on() handler and must be attached directly to a DateField instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date field myDF, sends “_level0.myDF” to the Output panel: on(scroll){ trace(this); }
The second usage example uses a dispatcher/listener event model. A component instance (myDF) dispatches an event (in this case, scroll) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has properties that contain information about the event. You can use these properties to write code that handles the event. The scroll event’s event object has an additional property, detail, that can have one of the following values: nextMonth, previousMonth, nextYear, previousYear. Finally, you call the EventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called. For more information, see “EventDispatcher class” on page 415. Example
This example, written on a frame of the Timeline, sends a message to the Output panel when a user clicks a month button on a DateField instance called myDF. The first line of code creates a listener object called form. The second line defines a function for the scroll event on the listener object. Inside the function is a trace() statement that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event—in this example, myDF. The last line calls EventDispatcher.addEventListener() from myDF and passes it the scroll event and the form listener object as parameters. form = new Object(); form.scroll = function(eventObj){ trace(eventObj.detail); } myDF.addEventListener("scroll", form);
DateField component (Flash Professional only)
385
DateField.selectableRange Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.selectableRange Description
Property; sets a single selectable date or a range of selectable dates. The value of this property is an object that consists of two Date objects named rangeStart and rangeEnd. The rangeStart and rangeEnd properties designate the boundaries of the selectable date range. If only rangeStart is defined, all the dates after rangeStart are enabled. If only rangeEnd is defined, all the dates before rangeEnd are enabled. The default value is undefined. If you want to enable only a single day, you can use a single Date object as the value of selectableRange.
Specify a full date when you define dates—for example, new Date(2003,6,24) rather than new Date(). If you don’t specify a full date, the time returns as 00:00:00. The value of DateField.selectedDate is set to undefined if it falls outside the selectable range. The values of DateField.displayedMonth and DateField.displayedYear are set to the nearest last month in the selectable range if the current month falls outside the selectable range. For example, if the current displayed month is August, and the selectable range is from June 2003 to July 2003, the displayed month will change to July 2003. Example
The following example defines the selectable range as the dates between and including May 7 and June 7: myDF.selectableRange = {rangeStart: new Date(2001, 4, 7), rangeEnd: new Date(2003, 5, 7)};
The following example defines the selectable range as the dates after and including May 7: myDF.selectableRange = {rangeStart: new Date(2003, 4, 7)};
The following example defines the selectable range as the dates before and including June 7: myDF.selectableRange = {rangeEnd: new Date(2003, 5, 7)};
The following example defines the selectable date as June 7 only: myDF.selectableRange = new Date(2003, 5, 7);
386
Chapter 6: Components Dictionary
DateField.selectedDate Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.selectedDate Description
Property; a Date object that indicates the selected date if that value falls within the value of the selectableRange property. The default value is undefined. Example
The following example sets the selected date to June 7: myDF.selectedDate = new Date(2003, 5, 7);
DateField.showToday Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage myDF.showToday Description
Property; a Boolean value that determines whether the current date is highlighted. The default value is true. Example
The following example turns off the highlighting on today’s date: myDF.showToday = false;
DateField component (Flash Professional only)
387
CHAPTER 6 Components Dictionary
Delegate class Inheritance
Object > Delegate
ActionScript Class Name
mx.utils.Delegate
The Delegate class lets you run a function in a specific scope. This class is provided so that you can dispatch the same event to two different functions (see “Delegating events to functions” on page 63), and so that you can call functions within the scope of the containing class. When you pass a function as a parameter to EventDispatcher.addEventListener(), the function is invoked in the scope of the broadcaster component instance, not the object in which it is declared (see “Delegating the scope of a function” on page 65). You can call Delegate.create() to call the function within the scope of the declaring object. Method summary for the Delegate class The following table lists the method of the Delegate class. Property
Description
Delegate.create()
A static method that allows you to run a function in a specific scope.
Delegate.create() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage Delegate.create(scopeObject, function) Parameters scopeObject function
A reference to an object. This is the scope in which to run the function.
A reference to a function.
Description
Method (static); allows you to delegate events to specific scopes and functions. Use the following syntax: import mx.utils.Delegate; compInstance.addEventListener("eventName", Delegate.create(scopeObject, function));
The scopeObject parameter specifies the scope in which the specified function is called. Example
For examples of Delegate.create(), see “Delegating events” on page 63.
388
Chapter 6: Components Dictionary
See also EventDispatcher.addEventListener()
Delegate class
389
Delta interface (Flash Professional only) ActionScript Interface Name
CHAPTER 6 Components Dictionary
mx.data.components.datasetclasses.Delta
The Delta interface provides access to the transfer object, collection, and transfer object-level changes. With this interface you can access the new and previous values in a transfer object. For example, if the delta packet was obtained from a data set, each delta would represent an added, edited, or deleted row. The Delta interface also provides access to messages returned by the associated server-side process. For more information on client-server interactions, see “RDBMSResolver component (Flash Professional only)” on page 636. Use the Delta interface to examine the delta packet before sending changes to the server and to review messages returned from server-side processing. Method summary for the Delta interface The following table lists the methods of the Delta interface. Method
Description
Delta.addDeltaItem()
Adds the specified DeltaItem instance.
Delta.getChangeList()
Returns an array of changes made to the current item.
Delta.getDeltaPacket()
Returns the delta packet that contains the delta.
Delta.getId()
Returns the unique ID of the current item within the DeltaPacket collection.
Delta.getItemByName()
Returns the specified DeltaItem object.
Delta.getMessage()
Returns the message associated with the current item.
Delta.getOperation()
Returns the operation that was performed on the current item within the original collection.
Delta.getSource()
Returns the transfer object on which the changes were performed.
Delta.addDeltaItem() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage delta.addDeltaItem(deltaitem) Parameters deltaitem
390
DeltaItem instance to add to this delta.
Chapter 6: Components Dictionary
Returns
Nothing. Description
Method; adds the specified DeltaItem instance. If the specified DeltaItem instance already exists, this method replaces it. Example
The following example calls the addDeltaItem() method: //... var d:Delta = new DeltaImpl("ID1345678", curItem, DeltaPacketConsts.Added, "", false); d.addDeltaItem(new DeltaItem(DeltaItem.Property, "ID", {oldValue:15, newValue:16})); //...
Delta.getChangeList() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage delta.getChangeList() Parameters
None. Returns
An array of associated DeltaItem instances. Description
Method; returns an array of associated DeltaItem instances. Each DeltaItem instance in the array describes a change made to the item. Example
The following example calls the getChangeList() method.: //... case mx.data.components.datasetclasses.DeltaPacketConsts.Modified: { // dpDelta is a variable of type Delta. var changes:Array = dpDelta.getChangeList(); for(var i:Number = 0; i
Delta interface (Flash Professional only)
391
} //...
Delta.getDeltaPacket() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage delta.getDeltaPacket() Parameters
None. Returns
The delta packet that contains this delta. Description
Method; returns the delta packet that contains this delta. This method lets you write code that can handle delta packets generically at the delta level. Example
The following example uses the getDeltaPacket() method to access the delta packet’s data source: while(dpCursor.hasNext()) { dpDelta = Delta(dpCursor.next()); trace("DeltaPacket source is: " + dpDelta.getDeltaPacket().getSource()); }
Delta.getId() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage delta.getId() Parameters
None. Returns
An object; returns the unique ID of this item within the DeltaPacket collection.
392
Chapter 6: Components Dictionary
Description
Method; returns a unique identifier for this item within the DeltaPacket collection. Use this ID in the source component for the delta packet to receive updates and make changes to items that the delta packet was generated from. For example, assuming that the DataSet component sends updates to a server and the server returns new key field values, this method allows the DataSet component to examine the resulting delta packet, find the original transfer object, and make the appropriate updates to it. Example
The following example calls the getId() method: while(dpCursor.hasNext()) { dpDelta = Delta(dpCursor.next()); trace("id ["+dpDelta.getId()+"]"); }
Delta.getItemByName() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage delta.getItemByName(name) Parameters name
A string that specifies the name of the property or method for the associated DeltaItem
object. Returns
The DeltaItem object specified by name. If no DeltaItem object is found that matches name, this method returns null. Description
Method; returns the DeltaItem object specified by name. When method calls or property changes on a transfer object are needed by name, this method provides the most efficient access. Example
The following example calls the getItemByName() method: private function buildFieldTag(deltaObj:Delta, field:Object, isKey:Boolean):String { var chgItem:DeltaItem = deltaObj.getItemByName(field.name); var result:String= "
Delta interface (Flash Professional only)
Flash MX Professional 2004. Usage delta.getMessage() Parameters
None. Returns
A string; returns the message associated with delta. Description
Method; returns the associated message for this delta. Typically this message is only populated if the delta packet has been returned from a server in response to attempted updates. For more information, see “RDBMSResolver component (Flash Professional only)” on page 636. Example
The following example calls the getMessage() method: //... var dpi:Iterator = dp.getIterator(); var d:Delta; while(dpi.hasNext()) { d= dpi.next(); trace(d.getMessage()); } //...
394
Chapter 6: Components Dictionary
Delta.getOperation() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage delta.getOperation() Parameters
None. Returns
A number; returns the operation that was performed on the item within the original collection. Description
Method; returns the operation that was performed on this item within the original collection. Valid values for this are DeltaPacketConsts.Added, DeltaPacketConsts.Removed, and DeltaPacketConsts.Modified. You must either import mx.data.components.datasetclasses.DeltaPacketConsts or fully qualify each constant. Example
The following example calls the getOperation() method: while(dpCursor.hasNext()) { dpDelta = Delta(dpCursor.next()); op=dpDelta.getOperation(); trace("DeltaPacket source is: " + dpDelta.getDeltaPacket().getSource()); switch(op) { case mx.data.components.datasetclasses.DeltaPacketConsts.Added: trace("***In case DeltaPacketConsts.Added ***"); case mx.data.components.datasetclasses.DeltaPacketConsts.Modified: { trace("***In case DeltaPacketConsts.Modified ***"); } }
Delta.getSource() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage delta.getSource()
Delta interface (Flash Professional only)
395
Parameters
None. Returns
The transfer object on which the changes were performed. Description
Method; returns the transfer object on which the changes were performed. Example
The following example calls the getSource() method: while(dpCursor.hasNext()) { dpDelta = Delta(dpCursor.next()); op=dpDelta.getOperation(); switch(op) { case mx.data.components.datasetclasses.DeltaPacketConsts.Modified: { // the original values are trace("Unmodified source is: "); var src = dpDelta.getDeltaPacket().getSource(); for(var i in src){ if(typeof(src[i]) != "function"){ trace(i+"="+src[i]); } } } }
396
Chapter 6: Components Dictionary
DeltaItem class (Flash Professional only) ActionScript Class Name
CHAPTER 6 Components Dictionary
mx.data.components.datasetclasses.DeltaItem
The DeltaItem class provides information about an individual operation performed on a transfer object. It indicates whether a change was made directly to a property of the transfer object or whether the change was made by a method call. It also provides the original state of properties on a transfer object. For example, if the source of the delta packet was a data set, the DeltaItem object contains information about any field that was edited. In addition to the above, a DeltaItem object can contain server response information such as current value and a message. Use the DeltaItem class when accessing the changes in a delta packet. To access these changes, use which returns an iterator of deltas. Each delta contains zero or more DeltaItem instances, which you can access through Delta.getItemByName() or Delta.getChangeList(). DeltaPacket.getIterator(),
Property summary for the DeltaItem class The following table lists the properties of the DeltaItem class. Property
Description
DeltaItem.argList
If a change is made through a method call, this is the array of values that were passed to the method. This property is readonly.
DeltaItem.curValue
If a change is made to a property, this is the current server value of the property. This property is read-only.
DeltaItem.delta
The associated delta for the DeltaItem object. This property is read-only.
DeltaItem.kind
The type of change.
DeltaItem.message
The server message associated with the DeltaItem object.
DeltaItem.name
The name of the property or method that changed. This property is read-only.
DeltaItem.newValue
If a change was made to a property, this is the new value of the property. This property is read-only.
DeltaItem.oldValue
If a change was made to a property, this is the old value of the property. This property is read-only.
DeltaItem.argList Availability
Flash Player 7. Edition
Flash MX Professional 2004.
DeltaItem class (Flash Professional only)
397
Usage deltaitem.argList Description
Property (read-only); an array of values passed to the change method. This property applies only if the change’s kind is DeltaItem.Method. DeltaItem.curValue Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaitem.curValue Description
Property (read-only); an object containing the current property value on the server’s copy of the transfer object. This property applies only if the change’s kind is DeltaItem.Property, and the property is relevant only in a delta that has been returned from a server and is being applied to the data set for user resolution. DeltaItem.delta Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaitem.delta Description
Property (read-only); a delta associated with the DeltaItem object. When a DeltaItem object is created, it is associated with a delta and adds itself to the delta’s list of changes. This property provides a reference to the delta that this item belongs to. DeltaItem.kind Availability
Flash Player 7. Edition
Flash MX Professional 2004.
398
Chapter 6: Components Dictionary
Usage deltaitem.kind Description
Property; a number that indicates the type of change. Use the following constants to evaluate this property:
• •
DeltaItem.Property DeltaItem.Method
The change was made to a property on the transfer object. The change was made through a method call on the transfer object.
DeltaItem.message Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaitem.message Description
Property; a string containing a server message associated with this DeltaItem object. This can be any message for the property or method call change attempted in the delta packet. This message is usually relevant only in a delta that has been returned from a server and is being applied to the DataSet for resolution. DeltaItem.name Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaitem.name Description
Property (read-only); a string containing the name of the changed property (if the change’s kind is DeltaItem.Property) or the name of the method that made the change (if the change’s kind is DeltaItem.Method).
DeltaItem class (Flash Professional only)
399
DeltaItem.newValue Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaitem.newValue Description
Property (read-only); an object containing the new value of the property. This property applies only if the change’s kind is DeltaItem.Property. DeltaItem.oldValue Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaitem.oldValue Description
Property (read-only); an object containing the old value of the property. This property applies only if the change’s kind is DeltaItem.Property.
400
Chapter 6: Components Dictionary
CHAPTER 6 Components Dictionary
DeltaPacket interface (Flash Professional only) ActionScript Interface Name
mx.data.components.datasetclasses.DeltaPacket
The DeltaPacket interface is provided by the deltaPacket property of the DataSet component, which is part of the data management functionality in Flash MX Professional 2004. (For more information, see Chapter 14, “Data Integration (Flash Professional Only),” in Using Flash). Typically the delta packet is used internally by resolver components.The DeltaPacket interface and the related Delta interface and DeltaItem class let you manage changes made to the data. These components have no visual appearance at runtime. A delta packet is an optimized set of instructions that describe all changes that have been made to the data in a data set. When the DataSet.applyUpdates() method is called, the DataSet component populates the DataSet.deltaPacket property. Typically, this property is connected (by data binding) to a resolver component such as RDBMSResolver. The resolver converts the delta packet into an update packet in the appropriate format. Note: Unless you are writing your own custom resolver, it is unlikely you will ever need to know about or write code that accesses methods or properties of a delta packet.
A delta packet contains one or more deltas (see “Delta interface (Flash Professional only)” on page 390), and each delta contains zero or more delta items (see “DeltaItem class (Flash Professional only)” on page 397). Method summary for the DeltaPacket interface The following table lists the methods of the DeltaPacket interface. Method
Description
DeltaPacket.getConfigInfo()
Returns configuration information that is specific to the implementation of the DeltaPacket interface.
DeltaPacket.getIterator()
Returns the iterator for the delta packet that iterates through the delta packet’s list of deltas.
DeltaPacket.getSource()
Returns the source of the delta packet. This is the component that has exposed this delta packet.
DeltaPacket.getTimestamp()
Returns the date and time at which the delta packet was instantiated.
DeltaPacket.getTransactionId()
Returns the transaction ID for this delta packet.
DeltaPacket.logChanges()
Indicates whether the consumer of the delta packet should log the changes it specifies.
DeltaPacket.getConfigInfo() Availability
Flash Player 7. Edition
Flash MX Professional 2004.
DeltaPacket interface (Flash Professional only)
401
Usage deltaPacket.getConfigInfo(info) Parameters info
Object; contains information specific to the implementation.
Returns
An object that contains information required for the specific DeltaPacket implementation. Description
Method; returns configuration information that is specific to the implementation of the DeltaPacket interface. This method allows implementations of the DeltaPacket interface to access custom information. Example
The following example calls the getConfigInfo() method: // ... new DeltaPacketImpl(source, getTransactionId(), null, logChanges(), getConfigInfo()); // ...
DeltaPacket.getIterator() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaPacket.getIterator() Parameters
None. Returns
An interface to the iterator for the DeltaPacket collection that iterates through the delta packet’s list of deltas. Description
Method; returns the iterator for the DeltaPacket collection. This provides a mechanism for looping through the changes in the delta packet. For a complete description of this interface, see “Iterator interface (Flash Professional only)” on page 441.
402
Chapter 6: Components Dictionary
Example
The following example uses the getIterator() method to access the iterator for the deltas in a delta packet and uses a while statement to loop through the deltas: var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket; trace("*** Test deltapacket. Trans ID is: " + deltapkt.getTransactionId() + " ***"); var OPS:Array = new Array("added", "removed", "modified"); var dpCursor:Iterator = deltapkt.getIterator(); var dpDelta:Delta; var op:Number; var changeMsg:String; while(dpCursor.hasNext()) { dpDelta = Delta(dpCursor.next()); op=dpDelta.getOperation(); }
DeltaPacket.getSource() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaPacket.getSource() Parameters
None. Returns
An object; the source of the DeltaPacket collection. This object is typically a descendant of MovieClip, but this is not required. For example, if the source is a data set, this object might be _level0.myDataSet. Description
Method; returns the source of the DeltaPacket collection. Example
The following example calls the getSource() method: // ... var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket; var dpSourceText:String = "Source: " + deltapkt.getSource(); trace(dpSourceText); // ...
DeltaPacket interface (Flash Professional only)
403
DeltaPacket.getTimestamp() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaPacket.getTimestamp() Parameters
None. Returns
A Date object containing the date and time at which the delta packet was created. Description
Method; returns the date and time at which the delta packet was created. Example
The following example calls the getTimestamp() method: // ... var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket; var dpTime:String = " Time: " + deltapkt.getTimestamp(); trace(dpTime); // ...
DeltaPacket.getTransactionId() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaPacket.getTransactionId() Parameters
None. Returns
A string; the unique transaction ID for a single transaction grouping of delta packets.
404
Chapter 6: Components Dictionary
Description
Method; returns the transaction ID for the delta packet. This unique identifier is used to group a send/receive transaction for a delta packet. The data set uses this to determine if the delta packet is part of the same transaction it originated with the DataSet.applyUpdates() call. Example
The following example calls the getTransactionId() method: // ... var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket; trace("*** Trans ID is: " + deltapkt.getTransactionId() + " ***"); // ...
DeltaPacket.logChanges() Availability
Flash Player 7. Edition
Flash MX Professional 2004. Usage deltaPacket.logChanges() Parameters
None. Returns
A Boolean value; true if the consumer of the delta packet should log changes found in the delta packet. Description
Method; returns true if the consumer of this delta packet should log the changes it specifies. This value is used mainly for communication of changes between data sets by means of shared objects or from a server to a local data set. In both cases, the data set should not record the changes specified. Example
The following example calls the logChanges() method: var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket; if(deltapkt.logChanges()) { trace("*** We need to log changes. ***"); } else { trace("*** We do not need to log changes"); }
DeltaPacket interface (Flash Professional only)
405
CHAPTER 6 Components Dictionary
DepthManager class ActionScript Class Name
mx.managers.DepthManager
The DepthManager class allows you manage the relative depth assignments of any component or movie clip, including _root. It also lets you manage reserved depths in a special highest-depth clip on _root for system-level services such as the cursor or tooltips. In general, the Depth Manager manages components automatically. You do not need to use its APIs unless you are an advanced Flash developer. The following methods constitute the relative depth-ordering API:
One of the following values: DepthManager.kTop, DepthManager.kBottom, All depth flags are static properties of the DepthManger class. You must either reference the DepthManager package (for example, mx.managers.DepthManager.kTopmost), or use the import statement to import the DepthManager package. depthFlag
DepthManager.kTopmost, DepthManager.kNotopmost.
initObj
An initialization object. This parameter is optional.
Returns
A reference to the object created. The return type is MovieClip. Description
Method; creates a child instance of the symbol specified by linkageName at the depth specified by depthFlag.
DepthManager class
407
Example
The following example creates a minuteHand instance of the MinuteSymbol movie clip and places it in front of the clock: import mx.managers.DepthManager; minuteHand = clock.createChildAtDepth("MinuteSymbol", DepthManager.kTop);
A class name. This parameter is a of type Function.
One of the following values: DepthManager.kTop, DepthManager.kBottom, All depth flags are static properties of the DepthManger class. You must either reference the DepthManager package (for example, mx.managers.DepthManager.kTopmost), or use the import statement to import the DepthManager package. depthFlag
DepthManager.kTopmost, DepthManager.kNotopmost.
initObj
An initialization object. This parameter is optional.
Returns
A reference to the created child. The return type is UIObject. Description
Method; creates a child of the class specified by className at the depth specified by depthFlag. Example
The following code draws a focus rectangle in front of all NoTopmost objects: import mx.managers.DepthManager this.ring = createClassChildAtDepth(mx.skins.RectBorder, DepthManager.kTop);
The following code creates an instance of the Button class and passes it a value for its label property as an initObj parameter: import mx.managers.DepthManager button1 = createClassChildAtDepth(mx.controls.Button, DepthManager.kTop, {label: "Top Button"});
depthSpace One of the following values: DepthManager.kCursor, DepthManager.kTooltip. All depth flags are static properties of the DepthManger class. You must either reference the DepthManager package (for example, mx.managers.DepthManager.kCursor), or use the import statement to import the DepthManager package. initObj
An initialization object. This parameter is optional.
Returns
A reference to the created object. The return type is UIObject. Description
Method; creates an object of the class specified by className at the depth specified by depthSpace. This method is used for accessing the reserved depth spaces in the special highestdepth clip. Example
The following example creates an object from the Button class: import mx.managers.DepthManager myCursorButton = createClassObjectAtDepth(mx.controls.Button, DepthManager.kCursor, {label: "Cursor"});
A linkage identifier. This parameter is of type String.
DepthManager class
409
depthSpace One of the following values: DepthManager.kCursor, DepthManager.kTooltip. All depth flags are static properties of the DepthManger class. You must either reference the DepthManager package (for example, mx.managers.DepthManager.kCursor), or use the import statement to import the DepthManager package. initObj
An optional initialization object.
Returns
A reference to the created object. The return type is MovieClip. Description
Method; creates an object at the specified depth. This method is used for accessing the reserved depth spaces in the special highest-depth clip. Example
The following example creates an instance of the TooltipSymbol symbol and places it at the reserved depth for tooltips: import mx.managers.DepthManager myCursorTooltip = createObjectAtDepth("TooltipSymbol", DepthManager.kTooltip);
DepthManager.kBottom Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage DepthManager.kBottom Description
Property (static); a property with the constant value 202. This property is passed as a parameter in calls to DepthManager.createClassChildAtDepth() and DepthManager.createChildAtDepth() to place content behind other content. DepthManager.kCursor Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage DepthManager.kCursor
410
Chapter 6: Components Dictionary
Description
Property (static); a property with the constant value 101. This property is passed as a parameter in calls to DepthManager.createClassObjectAtDepth() and DepthManager.createObjectAtDepth() to request placement at cursor depth. DepthManager.kNotopmost Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage DepthManager.kNotopmost Description
Property (static); a property with the constant value 204. This property is passed as a parameter in calls to DepthManager.createClassChildAtDepth() and DepthManager.createChildAtDepth() to request removal from the topmost layer. DepthManager.kTooltip Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage DepthManager.kTooltip Description
Property (static); a property with the constant value 102. This property is passed as a parameter in calls to DepthManager.createClassObjectAtDepth() and DepthManager.createObjectAtDepth() to place an object at the tooltip depth. DepthManager.kTop Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage DepthManager.kTop
DepthManager class
411
Description
Property (static); a property with the constant value 201. This property is passed as a parameter in calls to DepthManager.createClassChildAtDepth() and DepthManager.createChildAtDepth() to request placement on top of other content but below DepthManager.kTopmost content. DepthManager.kTopmost Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX Professional 2004. Usage DepthManager.kTopmost Description
Property (static); a property with the constant value 203. This property is used in calls to DepthManager.createClassChildAtDepth() and DepthManager.createChildAtDepth() to request placement on top of other content, including DepthManager.kTop objects. DepthManager.setDepthAbove() Availability
An instance name. This parameter is of type MovieClip.
Returns
Nothing. Description
Method; sets the depth of a movie clip or component instance above the depth of the instance specified by the instance parameter and moves other objects if necessary.
412
Chapter 6: Components Dictionary
DepthManager.setDepthBelow() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004 and Flash MX Professional 2004. Usage movieClipInstance.setDepthBelow(instance) Parameters instance
An instance name. This parameter is of type MovieClip.
Returns
Nothing. Description
Method; sets the depth of a movie clip or component instance below the depth of the specified instance and moves other objects if necessary. Example
The following code sets the depth of the textInput instance below the depth of button: textInput.setDepthBelow(button);
Method; sets the depth of movieClipInstance to the value specified by depth. This method moves an instance to another depth to make room for another object.
DepthManager class
413
Example
The following example sets the depth of the mc1 instance to a depth of 10: mc1.setDepthTo(10);
For more information about depth and stacking order, see “Determining the next highest available depth” in Using ActionScript in Flash.
414
Chapter 6: Components Dictionary
CHAPTER 6 Components Dictionary
EventDispatcher class
Events let your application know when the user has interacted with a component, and when important changes have occurred in the appearance or life cycle of a component—such as its creation, destruction, or resizing. The methods of the EventDispatcher class let you add and remove event listeners so that your code can react to events appropriately. For example, you use the EventDispatcher.addEventListener() method to register a listener with a component instance. The listener is invoked when a component’s event is triggered. If you want to write a custom object that emits events that aren’t related to the user interface, EventDispatcher is smaller and faster to use as a mix-in for UIComponent than UIEventDispatcher. Event objects An event object is passed to a listener as a parameter. The event object is an ActionScript object that has properties that contain information about the event that occurred. You can use the event object inside the listener callback function to access the name of the event that was broadcast, or the instance name of the component that broadcast the event. For example, the following code uses the target property of the evtObj event object to access the label property of the myButton instance and send the value to the Output panel: listener = new Object(); listener.click = function(evtObj){ trace("The " + evtObj.target.label + " button was clicked"); } myButton.addEventListener("click", listener);
Some event object properties are defined in the W3C specification (www.w3.org/TR/DOMLevel-3-Events/events.html) but aren’t implemented in version 2 of the Macromedia Component Architecture. Every version 2 event object has the properties listed in the table below. Some events have additional properties defined, and if so, the properties are listed in the event’s entry. Property
Description
type
A string indicating the name of the event.
target
A reference to the component instance broadcasting the event.
EventDispatcher class (API) ActionScript Class Name
mx.events.EventDispatcher
EventDispatcher class
415
Method summary for the EventDispatcher class The following table lists the methods of the EventDispatcher class. Method
Description
EventDispatcher.addEventListener()
Registers a listener with a component instance.
EventDispatcher.dispatchEvent()
Dispatches an event programmatically.
EventDispatcher.removeEventListener() Removes an event listener from a component
instance.
EventDispatcher.addEventListener() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004 and Flash MX Professional 2004. Usage componentInstance.addEventListener(event, listener) Parameters event
A string that is the name of the event.
listener
A reference to a listener object or function.
Returns
Nothing. Description
Method; registers a listener object with a component instance that is broadcasting an event. When the event occurs, the listener object or function is notified. You can call this method from any component instance. For example, the following code registers a listener to the component instance myButton: myButton.addEventListener("click", myListener);
You must define the listener as either an object or a function before you call addEventListener() to register the listener with the component instance. If the listener is an object, it must have a callback function defined that is invoked when the event occurs. Usually, that callback function has the same name as the event with which the listener is registered. If the listener is a function, the function is invoked when the event occurs. For more information, see “Using listeners to handle events” on page 56.
416
Chapter 6: Components Dictionary
You can register multiple listeners to a single component instance, but you must use a separate call to addEventListener() for each listener. Also, you can register one listener to multiple component instances, but you must use a separate call to addEventListener() for each instance. For example, the following code defines one listener object and assigns it to two Button component instances, whose label properties are button1 and button2, respectively: lo = new Object(); lo.click = function(evt){ trace(evt.target.label + " clicked"); } button1.addEventListener("click", lo); button2.addEventListener("click", lo);
Execution order is not guaranteed. You cannot expect one listener to be called before another. An event object is passed to the listener as a parameter. The event object has properties that contain information about the event that occurred. You can use the event object inside the listener callback function to access information about the type of event that occurred and which instance broadcast the event. In the example above, the event object is evt (you can use any identifier as the event object name), and it is used in the if statements to determine which button instance was clicked. For more information, see “About the event object” on page 66. Example
The following example defines a listener object, myListener, and defines the callback function for the click event. It then calls addEventListener() to register the myListener listener object with the component instance myButton. myListener = new Object(); myListener.click = function(evt){ trace(evt.type + " triggered"); } myButton.addEventListener("click", myListener);
To test this code, place a Button component on the Stage with the instance name myButton, and place this code in Frame 1. EventDispatcher.dispatchEvent() Availability
Flash Player 6 (6.0 79.0). Edition
Flash MX 2004 and Flash MX Professional 2004. Usage dispatchEvent(eventObject)
EventDispatcher class
417
Parameters eventObject A reference to an event object. The event object must have a type property that is a string indicating the name of the event. Generally, the event object also has a target property that is the name of the instance broadcasting the event. You can define other properties on the event object that will help a user capture information about the event when it is dispatched. Returns
Nothing. Description
Method; dispatches an event to any listener registered with an instance of the class. This method is usually called from within a component’s class file. For example, the SimpleButton.as class file dispatches the click event. Example
The following example dispatches a click event: dispatchEvent({type:"click"});
Flash MX 2004 and Flash MX Professional 2004. Usage componentInstance.removeEventListener(event, listener) Parameters event
A string that is the name of the event.
listener
A reference to a listener object or function.
Returns
Nothing. Description
Method; unregisters a listener object from a component instance that is broadcasting an event.
418
Chapter 6: Components Dictionary
FocusManager class
CHAPTER 6 Components Dictionary
You can use the Focus Manager to specify the order in which components receive focus when a user presses the Tab key to navigate in an application. You can also use the Focus Manager to set a button in your document that receives keyboard input when a user presses Enter (Windows) or Return (Macintosh). For example, when users fill out a form, they should be able to tab between fields and press Enter (Windows) or Return (Macintosh) to submit the form. All components implement Focus Manager support; you don’t need to write code to invoke it. The Focus Manager interacts with the System Manager, which activates and deactivates FocusManager instances as pop-up windows are activated or deactivated. Each modal window has an instance of FocusManager so the components in that window become their own tab set, preventing the user from tabbing into components in other windows. The Focus Manager recognizes groups of radio buttons (those with a defined RadioButton.groupName property) and sets focus to the instance in the group that has a selected property that is set to true. When the Tab key is pressed, the Focus Manager checks to see if the next object has the same group name as the current object. If it does, it automatically moves focus to the next object with a different group name. Other sets of components that support a groupName property can also use this feature. The Focus Manager handles focus changes caused by mouse clicks. If the user clicks a component, that component is given focus. Using the Focus Manager The Focus Manager does not automatically assign focus to a component. You must write a script that calls FocusManager.setFocus() on a component if you want a component to have focus when an application loads. Note: If you call FocusManager.setFocus() to set focus to a component when an application loads, the focus ring does not appear around that component. The component has focus, but the indicator is not present.
To create focus navigation in an application, set the tabIndex property on any objects (including buttons) that should receive focus. When a user presses the Tab key, the Focus Manager looks for an enabled object with a tabIndex property that is higher than the current value of tabIndex. Once the Focus Manager reaches the highest tabIndex property, it returns to zero. So, in the following example, the comment object (probably a TextArea component) receives focus first, and then the okButton object receives focus: comment.tabIndex = 1; okButton.tabIndex = 2;
You can also use the Accessibility panel to assign a tab index value. If nothing on the Stage has a tab index value, the Focus Manager uses the depth (stacking order, or z-order). The depth is set up primarily by the order in which components are dragged to the Stage; however, you can also use the Modify > Arrange > Bring to Front/Send to Back commands commands to determine the final depth.
FocusManager class
419
To create a button that receives focus when a user presses Enter (Windows) or Return (Macintosh), set the FocusManager.defaultPushButton property to the instance name of the desired button, as shown here: focusManager.defaultPushButton = okButton; Note: The Focus Manager is sensitive to when objects are placed on the Stage (the depth order of objects) and not their relative positions on the Stage. This is different from the way Flash Player handles tabbing.
Using the Focus Manager to allow tabbing You can use the Focus Manager to create a scheme that allows users to press the Tab key to cycle through objects in a Flash application. (Objects in the tab scheme are called tab targets.) The Focus Manager examines the tabEnabled and tabChildren properties of the objects’ parents in order to locate the objects. A movie clip can be either a container of tab targets, a tab target itself, or neither: Movie clip type
tabEnabled
tabChildren
Container of tab targets
false
true
Tab target
true
false
Neither
false
false
Note: This is different from the default Flash Player behavior, in which a container’s tabChildren property can be undefined.
Consider the following scenario. On the Stage of the main Timeline are two text fields (txt1 and txt2) and a movie clip (mc) that contains a DataGrid component (grid1) and another text field (txt3). You would use the following code to allow users to press Tab and cycle through the objects in the following order: txt1, txt2, grid1, txt3. Note: The FocusManager and TextField instances are enabled by default. // let Focus Manager know mc has children; // this overrides mc.focusEnabled=true; mc.tabChildren=true; mc.tabEnabled=false; // set the tabbing sequence txt1.tabIndex = 1; txt2.tabIndex = 2; mc.grid1.tabIndex = 3; mc.txt3.tabIndex = 4; // set initial focus to txt1 txt1.text = "focus"; focusManager.setFocus(txt1);
If your movie clip doesn’t have an onPress or onRelease method or a tabEnabled property, it won’t be seen by the Focus Manager unless you set focusEnabled to true. Input text fields are always in the tab scheme unless they are disabled.
420
Chapter 6: Components Dictionary
If a Flash application is playing in a web browser, the application doesn’t have focus until a user clicks somewhere in the application. Also, once a user clicks in the Flash application, pressing Tab can cause focus to jump outside the Flash application. To keep tabbing limited to objects inside the Flash application in Flash Player 7 ActiveX control, add the following parameter to the HTML