Page 1


Flex 3: ™

A Beginner’s Guide Michele E. Davis Jon A. Phillips

New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto


Copyright © 2008 by The McGraw-Hill Companies. All rights reserved. Manufactured in the United States of America. Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher. 0-07-160364-6 The material in this eBook also appears in the print version of this title: 0-07-154418-6. All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps. McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-hill.com or (212) 904-4069. TERMS OF USE This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms. THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise. DOI: 10.1036/0071544186


Professional

Want to learn more? We hope you enjoy this McGraw-Hill eBook! If you’d like more information about this book, its author, or related books and websites, please click here.


As always we thank Simon, Mimi, and Zack while we worked as consultants by day and authors by night.


About the Authors Michele E. Davis has co-authored and authored more than 18 books and has a PhD in English and French. Davis is a full-time consultant in Instructional Design, Technical Writing, and Web Development and Training. She’s worked for General Mills, Toro, Affiliated Computer Services, LookSmart, Medtronic, and many more corporations. Davis is a career writer, having published her first poem for a fiver while in second grade. She can be found on the web at www.krautgrrl.com. Jon A. Phillips has a BS in Computer Science, having started programming in grade school. This is the fifth book he’s written with Davis. He’s worked with numerous web technologies as well as a substantial amount of database development from Oracle to MySQL. Phillips is always looking for the best technologies to solve real-world computing problems, which includes working with Flex. Phillips is also a full-time consultant and has worked for Emerson Process, Siemens, Affiliated Computer Services, The University of Minnesota, and Lockheed Martin. He can be found on the web at www.krautboy.com.


For more information about this title, click here

Contents ACKNOWLEDGMENTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

xi xiii

1 Flex Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Origins of Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Understanding Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . LiveCycle Data Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using LiveCycle Data Services with the Flex Builder . . . . . . . . . . . . . . . . . . . . . Flex’s Forte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Object Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Consistent API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Open Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flex Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flex vs. HTML/Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dynamic HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DOMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cross-Platform Support with Single Binary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flex Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Initial Releases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adobe Flex 2.01 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adobe Flex 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How Flex Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Design and Configure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Securing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1

2 Installation and Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Installing Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flex Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flex Builder Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flex SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Apache/IIS Runtime Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

v

3 4 4 5 5 8 10 10 11 11 11 11 12 13 13 13 13 14 14 15 15 16 16 17 17 18 19

21 22 22 23 23 24


vi

Flex 3: A Beginner’s Guide

Installing Flex Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Macintosh OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flex Builder Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Workspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Managing Projects in a Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Test Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . General Requirements for the SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Downloading the SDK Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Removing the Flash Plug-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Installing the Flex SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Running Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Apache/IIS Flex Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Installer Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Testing the Compiler Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

25 28 30 30 30 31 37 38 38 39 41 42 43 43 46

3 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Principles of MXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Principles of ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ActionScript Timeline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Proper Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modifying Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Functions and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Testing Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Named Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flow Control and Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Event Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Create an Event Handler That Displays an Alert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MXML Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

47 49 50 50 51 52 54 54 54 55 56 57 57 58 58 59 61 61 62 63 65 65 67 67 67 67 70 70


Contents

Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Class Specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Understanding MXML Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Flex Config File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Manifest File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Referencing Namespaces in Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

72 74 75 75 76 76 76 77

4 Working with Flex Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flex Builder Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Building a User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Application Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constraint-Based Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Text-Based Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Provider Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Menu Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modifying Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Class Hierarchy of Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sizing Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Positioning Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing the Appearance of Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Text Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Text Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The htmlText Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Select and Modify Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TextArea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TextInput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . RichTextEditor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Label Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Menu Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Menu Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Provider Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Menu Control Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MenuBar Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Create a MenuBar Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Running Your Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

79 81 82 84 86 86 87 87 90 92 93 94 94 96 97 97 99 99 100 100 101 101 102 102 104 104 105 106 106 107 109 109 112

5 States, Transitions, and Behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 States and Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

vii


viii

Flex 3: A Beginner’s Guide

Creating States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Apply States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Event Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Effects and Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Transition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Invoke Using Flex Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Fading in a RichTextEditor with a Button Click . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Composite Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Binding Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Referencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

118 118 123 123 123 124 125 128 129 131 131 133 134 134 135

6 Modifying Your Application’s Appearance . . . . . . . . . . . . . . . . . . . . . . . . . . Categories of Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Styles and Skins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Enhanced Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CSS Property Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Skins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Graphical Skinning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

139

7 Data Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Local Versus Remote Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Security Implications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cross-Domain File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XML HTTP Service Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating an Application to Display Amazon Vampire Books . . . . . . . . . . . . . . . . . . . . . Proxy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Getting the Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

159

8 Debugging and Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Saving and Loading Profiling Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Live Objects Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Memory Snapshot Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loitering Objects Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Object References Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Allocation Trace Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Performance Snapshot Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Launch Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

179

141 141 142 144 145 149 154 154 161 161 162 164 166 166 170 181 187 188 190 191 193 194 196 198


Contents

Debugging with fdb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Launching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging with Trace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

200 201 203 206

9 Working with Media Assets/Deploying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Managing Media Assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Embedding vs. Runtime Referencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Supported Media Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Playing Embedded Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Playing Referenced Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Including a Referenced Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Including an Embedded Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Embedding Movies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Wrappers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Publishing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

209

A ActionScript and MXML Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ActionScript 3.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Global Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Global Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Global ActionScript Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Language Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MXML-Only Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Keyboard Shortcuts in Flex Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Online Communities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Quick Reference Sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interesting Flex-Based Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

229

211 211 212 213 213 216 217 218 219 220 220 223 230 230 232 232 234 243 244 246 246 247 248 249 249

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Index

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

ix


This page intentionally left blank


Acknowledgments J

ereme Allen, our technical editor, told me that he learned a lot from this book, and that is the best compliment a writing duo can receive from anyone. Allen did a great job of tech editing and performed lightening fast turnaround. Matt Wagner of Fresh Books brings us the sweetest books to write and has been our wonderful agent for a long time; one could only be so lucky to have a man like Wagner in your camp. Roger Stewart and Carly Stapleton at McGraw-Hill Professional made writing this book fun and interesting. Stewart made me laugh, and Stapleton kept Jon and I on track with our deadlines. Both of them were also incredibly supportive, have excellent communication skills, and were always open to new ideas for the book. Jody McKenzie from the Editorial/Production Department and our copy editor, Bob Campbell, helped make this book a work of art. The production team’s layout and design are stunning, and Campbell, thankfully, put our writing through heavy scrutiny. Our RSS feed information about Vampires was prompted by my friends from the good old days, along with the music of Cruxshadows, Nick Cave, The Lies, The Mission UK, and She Wants Revenge. Lastly, thanks to all of the hard-working developers at Adobe and the Adobe online Flex community for making Flex what it is today.

xi


This page intentionally left blank


Introduction W

ith the recent release of Flex Builder 3, now is the perfect time to start experimenting with Rich Internet Applications, or RIAs for short. RIAs provide an easy consistent way to provide a Web 2.0 experience to anyone using your Flex applications. Because they run on the ubiquitous Flash Player, a lot of the drudgery of determining the end user’s browser is a moot point. Starting out is easy and inexpensive, as Adobe offers both a 30-day free trial for Flex Builder and unlimited use of the Software Development Kit (SDK).

The Contents This book walks the reader through all of the steps that a beginning user must tackle, including which software to install, how to install it, and how to start writing code. It’s assumed that the reader has some knowledge of how the web works and has worked with plain old HTML. The differences between using Flex, HTML, and Ajax are dissected in easy-to-understand terms. All the major starting points of developing RIAs in Flex are covered, including a detailed description of the ActionScript programming language that forms the basis for Flex applications. The Flex framework, which speeds application development time, is discussed after you’ve learned about the Flex architecture and supporting languages. Each step of the way is written to make sometimes complex concepts easy to understand. Because Flex excels at working with media assets such as video and sound combined with dynamic data to create a rich Web 2.0 experience, the book introduces the necessary concepts to create these applications. Those concepts include working with sounds and

xiii


xiv

Flex 3: A Beginner’s Guide

video as well as working with dynamic data sources such as an RSS feed. With a solid starting point, the options for creating Flex applications are endless. Finally, practical advice is provided to help debug and publish applications once you’re cranking out applications that you’re ready to share with your friends and colleagues.

The Source Code The source code for examples in the book is downloadable on the web from www. mhprofessional.com. Any example of more than a few lines should be downloaded from the source code to reduce the time required to type in the code and to avoid any errors from typing in the code. The source code and related media assets are split out by chapter number. For code segments that have a heading with a listing number, the code is placed in a file called Listing<chapter number>_<listing number>. ActionScript files are named the same as the example’s class name, since Flex requires the filename to match the class definition. MXML code listings that are not large enough to warrant their being referred as a listing in the text are named Example<chapter number>_<description>, where description provides guidance on which example is being reference in the text. Any media assets are also named the same as their references in the text. In general, MXML examples can be run in the same project as other examples from the text. The ActionScript files that demonstrate importing sounds and SWF media assets should be created as ActionScript projects for each example. Flex Builder automatically places some default code when creating a new MXML or ActionScript file, but it’s okay to overwrite this default code with the source from the files provided with the book.


Chapter

1

Flex Fundamentals

1


2

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

The Origins of Flex

Understanding Flex

Flex’s Forte

Flex Limitations

Flex vs. HTML/Ajax

Cross Platform Support with Single Binary

Flex Versions

How Flex Works

W

orking with Adobe Flex is going to be an exciting journey. We’ll discuss Flash and Flex, MXML, and ActionScript, as well as what Flex is good at doing and how you can exploit the application for your web site. We’ll provide some simple sample code for a Hello World example that you can re-create using the Flex Online Developer. You’ll learn about the limitations of Flex but also gain a basic understanding about how to design, configure, build, deploy, and finally secure your Flex application. Flex is limited to a certain extent on what Flash can do, but Flex is an amazing way to create dynamic, rich Internet application web sites. Flex is being used in a wide variety of web sites, including Yahoo maps. For example, you can enter one address and see its location or enter an address, city, and state for two locations and get an overview of directions by going to http://maps.yahoo.com. HTML won’t allow you to zoom in and out without a page refresh, or reposition the map by clicking and moving your cursor, but Flex happily allows you to do this, with great benefit to the end user. As an example, try out the Color Visualizer from the Paint Online section of the Sherwin Williams web site, located at www.sherwin-williams.com/pro, which enables you to paint an exterior or an interior, demonstrating how specific colors look in each of those scenarios using Flex.


Chapter 1:

Flex Fundamentals

Many of the topics broached here are described in much greater detail throughout the book. Also, a glossary at the end of the book describes in detail terms you may not be familiar with and defines them for you.

The Origins of Flex Originally Flash content was created with the Flash multimedia-authoring program. Flash supports various capabilities for both vector and raster graphics, the scripting language ActionScript, and also bidirectional audio and video streaming. Additionally, there are versions of the Flash Player for mobile phones and other non-PC devices. Strictly speaking, however, Adobe Flash Professional is an integrated development environment (IDE) and the Flash Player itself is a virtual machine that an end user exploits to run Flash files. You can also speak of “running” Flash files as “parsing” them, and we’ll get into that later in this book. In our technology-driven environment Flash really can refer to the authoring environment, the player, or the application files. Unfortunately, Flash was designed with graphic artists in mind and uses a timeline concept that is foreign to most developers. Flex grew out of the need for a toolkit to create Flash content that developers understand. Flex provides this by using a workflow and programming model instead of the timeline. Flex was initially released as a J2EE application or JSP tag library that compiles a tagged-based language called MXML and an object-oriented language called ActionScript directly into Flash applications, which in turn create binary SWF applications. SWF is an abbreviation for Small Web Format or Shockwave Flash. Each letter is usually pronounced individually, but most people that work with Flash or Adobe Captivate call it SWF, in common nomenclature a swiff file. The Flex compiler is still a J2EE application. The current Flex releases support the creation of static files that are compiled at authoring time and can be published online, forgoing the need for a server license. There are alternatives to Flex, such as Ajax, JavaFX, OpenLaszlo, Silverlight, XUL, and the ZK Framework. For ColdFusion and JSP developers, to use MXML makes sense. On the other hand, ActionScript should be familiar to Java and other OO developers. But don’t worry if you are just starting out—that’s what this book is for, to help beginners to Flex get up to speed as quickly as possible. Flash and Flex are both applications that give the user live data. This means that web users don’t have to call your web server again when they decide to change the way the page loads. If you were using JSP, ASP, or PHP to code your site, the web server would be consistently queried from the user, whereas if you design your web site in Flash or Flex, there is no need to ping the web server—anything your web user wants to do is live.

3


4

Flex 3: A Beginner’s Guide

ActionScript ActionScript is the object-oriented programming (OOP) language that you use in your Flash files to add interactivity to your applications. But ActionScript is also used by Flex. ActionScript, like most programming languages, has its own grammar and punctuation rules, which determine the characters and words used to create meaning and the order in which they can be written. Take XML as an example: when you’re creating simple tags such as <b> for bold and <i> for italic, you need to close your bold tag first, then your italic tag. HTML doesn’t demand this kind of closing tag structure. In PHP, a semicolon (;) ends your code, and that’s exactly how you end a statement in ActionScript. ActionScript 1.0 was introduced in its current syntax when Flash 5 was released. This was the first thoroughly programmable version of Flash. When Flash 6 (MX) entered the scene, this broadened the programming environment by adding numerous built-in functions and allowing better programmatic control of movie elements. Flash 7 (MX 2004) introduced ActionScript 2.0, which added strong typing and class-based programming features. These features included explicit class declarations, inheritance, interfaces, and Strict Data Typing. Every release of ActionScript shares the same compiled form within the Flash output as an .swf. One difference between versions 1.0 and 2.0 of ActionScript is that version 2.0 is case sensitive. If you first capitalize a variable called Name in your code but later use a lowercase form for name, the different forms won’t match. ActionScript 3.2 has numerous changes from ActionScript 2.0. For example, some global functions such as call() and chr() have been removed in ActionScript 3.2 but were available in 2.0. You can see all the changes here: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/ migration.html.

MXML MXML is an XML-based user interface markup language first introduced by Macromedia in March 2004. Adobe, which acquired Macromedia in December 2005, kept the name, which some developers believe stands for “Multimedia eXtensible Markup Language.” Application developers use MXML in combination with ActionScript to develop rich Internet applications. You use MXML to lay out application interfaces, but it can also be used to create complex business logic and Rich Internet Application (RIA) behaviors. Some common practices are used by the specific usage of certain language syntax, such as the use of


Chapter 1:

Flex Fundamentals

curly braces ({}) to force an expression evaluation, and dot (.) notation to access properties or methods belonging to an object or movie segment. Currently, MXML is considered a proprietary standard because of its tight integration with Adobe technologies. MXML is often used with the Flex Server that dynamically compiles MXML into standard binary SWF files. However, both Adobe’s Flex Builder integrated development environment (IDE) and the free Flex Software Development Kit (SDK) can also generate SWF files from MXML that you can use without the Flex Server. Finally, the PHP PEAR package called XML_MXML wraps MXML in PHP to build Adobe Flex applications.

Understanding Flex The biggest reason to use Flex is that it allows web application developers to rapidly and easily build RIAs. Think of Flex this way: in a multitiered model, Flex applications serve as the presentation tier. Some examples of a multitiered model are a backend information source such as a Java process or a database, the application server (web server plus optional LiveCycle Data Services to talk to the info source tier), and the client (web browser/Flash plug-in). The client is also called the presentation layer. The application server is sometimes called the business logic layer.

LiveCycle Data Services LiveCycle Data Services provide an entire suite of comprehensive features that are data-enabled and are deployed using a Java web-based application. There is an entire messaging infrastructure for building data-rich Flex applications. This particular infrastructure is what underlies the LiveCycle Data Services features designed for moving data to and from specific applications. These include: RPC services, the Data Management Service, and the Message Service. Table 1-1 describes the various service types provided within the LiveCycle Data Services. We’re going to discuss more about understanding Flex, but we’ll also discuss later how LiveCycle Data Services work with Flex Builder. Flex comes bundled with various items, such as navigators that include a Tree Control, an Accordion Repeater, and a Tab Navigator. There are also charting and graphing components along with a data grid, and interactive effects such as fades and wipes. All of these are easy to use; you just pass them data and they handle all the

5


6

Flex 3: A Beginner’s Guide

Services

Description

RPC services

These are a call and response system in order to access external data. It helps you create applications that make remote service requests, and after they’re processed, data is returned to your Flex application.

Data Management Service

DMS provides data synchronization between real-time data updates, on-demand data paging, data replication, and integration through adapters to data. You can create applications that work with distributed data, and manage large collections of data as well as nested data relationships.

Message Service

This is a messaging service for real-time applications. You create applications that send and receive messages from other applications, such as Flex and Java Message Service (JMS).

Table 1-1 Service Types for LiveCycle Data Services

presentation. Of course, everything can be customized for whatever you’re creating for your end user. Since Flex is an RIA, you can do practically anything you want, enabling simple or complex interactions. For instance, your user can drag and drop an item to purchase into your existing shopping cart instead of clicking the currently standard Add To Cart button. While you may think this could be complicated, it really is easy to implement. Additionally, you can add sound that could talk a user through the user’s first interaction with your application. If you’d like to start playing around with Flex but aren’t ready to install it on your computer, you can use the Flex Online Compiler to try out Flex code (http://try.flex.org). The Flex Online Compiler allows you to type MXML and ActionScript code into a text window. When you click the Try It button, the code is compiled and executed online at the Flex Online Compiler server. You can write your own code or use code samples as a starting point.

NOTE At the time of this writing, the site was down for maintenance and may be down periodically.


Chapter 1:

Flex Fundamentals

Figure 1-1 shows the Flex Online Compiler after pressing the Try It button with code to create a Hello World application. The figure uses the code from Listing 1-1; don’t worry if you don’t understand it yet, but it’s here for your reference.

Figure 1-1 The Flex Online Compiler displaying a Hello World application

7


8

Flex 3: A Beginner’s Guide

Listing 1-1: Hello World Code <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" viewSourceURL="src/HelloWorld/index.html" horizontalAlign="center" verticalAlign="middle" width="350" height="150" > <mx:Panel paddingTop="15" paddingBottom="15" paddingLeft="15" paddingRight="15" title="Test Application" > <mx:Label text="Hello World!" fontWeight="bold" fontSize="20"/> </mx:Panel> </mx:Application>

Flex is designed to allow building rich Internet web applications quickly and reliably. You may already be familiar with the concept of a multitiered web application. A typical configuration includes the following: ●

A database server on one tier

An application server running a web server such as Apache and a server-side language such as PHP or ColdFusion

The client’s web browser with the capability to run JavaScript and plug-ins such as the Flash Player, also called the presentation tier

Flex fits into the last layer, the presentation tier, since it executes within the client’s web browser. Flex has many available components that make interaction with objects on the screen easy for the developer and the end user. Advanced interactions include the ability to drag and drop objects, charting, graphing, animation techniques, and fades. The overall user experience is improved because users don’t have to wait for a page refresh whenever they change something on the screen. HTML with logic on the application server page reloads to reflect user changes. Flex competes against several other technologies that aim to develop rich Internet applications. They include Ajax, OpenLaszlo, and Windows Presentation technologies. All of the platforms have their own individual strengths and weaknesses. Flex is gaining popularity, though, as Adobe continues to improve the product on the basis of community feedback.

Using LiveCycle Data Services with the Flex Builder The Flex Data Services/LiveCycle Data Services ES module works on the application server tier to enable Flex to access data from a database or other data sources such as


Chapter 1:

Flex Fundamentals

XML Web Services. It can talk to any data source that understands the Action Message Format, such as a Java class or ColdFusion component. It allows the Flash Player to interact with complex data on a remote server. Flex Builder has two ways to work with LiveCycle Data Services: ●

Compile an application in Flex Builder.

Save uncompiled application to a LiveCycle Data Services web application on the server and compile the application when the page is viewed.

If you compile a LiveCycle Data Services project in Flex Builder, it’s automatically saved as an SWF file to a LiveCycle Data Services web application on your server. To create a LiveCycle Data Services project, select New | Flex Project. Then select a configuration option from the Create A Flex Project dialog. Once you build a project, Flex creates a directory with the same name as your project, or your project takes on the existing name of the directory. As you probably figured, that directory is a subdirectory of the root folder you specified. Then a default MXML file, with the same name, is created, but you can select different MXML files as the default application file. In order to set the default application file in the Navigator tree, simply right-click (CONTROL-SHIFT on the Mac) and select Set As Default Application from the menu as shown in Figure 1-2. When you compile your applications locally, Flex Builder saves MXML files in the local Flex Builder project directory, but it saves SWF files and HTML wrapper files on the server. When you’re compiling applications on the server, your MXML files are saved on the server and no HTML wrapper file is generated when the application compiles. When using a Flex Builder project with a LiveCycle Data Services application, resources such as server-side Java classes are managed the same as they would be if you weren’t using Flex Builder. What’s handy is that you can specify locations of additional client-side source files, such as ActionScript classes, in the Source Path panel of the Flex Builder project properties dialog.

NOTE You need to specify a LiveCycle Data Services root folder and root URL, which map the root of a LiveCycle Data Services web application. Then before you compile your Flex application using Flex Builder, start the corresponding LiveCycle Data Services web application.

9


10

Flex 3: A Beginner’s Guide

Figure 1-2 Set As Default Application in the Navigator

Flex’s Forte There are many things that Flash and therefore Flex do well. Flex allows you to break out of the usual static web page and essentially embed mini-applications without the complexity and compatibility issues of alternatives like Java applets.

Audio Flex is particularly suited to integrating advanced video and audio effects into a web page. It may sound incredibly rudimentary, but if you try to add playback of sounds to a web page beyond just looping a sound in the background, you’ll find that it’s next to impossible to find a standard. Every browser handles sound controls differently and


Chapter 1:

Flex Fundamentals

accepts only certain sound formats. Even different browser versions have major changes in audio handling.

Video The Flash Player excels at video playback and control, with a wide range of supported video formats and compression types. Outside of Flash and Flex you’ll struggle to find video formats that are natively supported by the browser across different OSs and browsers.

Object Manipulation Because Flex completely controls the appearance and manipulation of objects on the screen, you have a high level of control over how your pages appear. Flex also supports many effects that are not always compatible outside of Flex, such as fading images and text.

Consistent API While plenty of developers work with other solutions for making web pages interactive, they tend to lack standards. Each framework is different from the next. They tend to lack a common basis. All of this makes your task of writing code more difficult.

Open Source Because the Flex API is an open-source framework, it tends be more consistent. You also have the advantage that if you don’t like the way the API does something, you can modify it yourself. The open-source components are as follows: ●

Flex Compiler

Flex Framework

Flex SDK The non-open-source components:

Flex Builder or Eclipse plug-in

Flex Charting

LiveCycle Data Services

11


12

Flex 3: A Beginner’s Guide

Flex Limitations As you know, Flex applications are really Flash applications, which means they’re limited by the constraints of the Flash Player. In particular, the Flash Player is not suited to producing vanilla documentation as HTML is. It’s also not supported as HTML on portable devices, although support is improving. The Flash Player cannot display anything outside the boundaries of the player’s space embedded in a web page. The size of the player window is determined by the HTML code that integrates the Flash file with the rest of the page. This can be a real pain, since it means your Flex application cannot make the screen bigger or smaller to suit the current interaction. It is possible to open a new Flash/Flex window using ActionScript to call JavaScript, but it’s rarely worth the complexity and hassle. It’s not currently possible to drag and drop files from the desktop to the Flash Player. Because the Flash Player is designed to work across a wide range of operating systems, it would be very difficult to support this functionality. Every OS has a different mechanism for how dragging and dropping works. This makes conveniences like displaying an image that’s been dropped onto the player impossible. Although Adobe publishes the format of SWF files, it still is the only entity that can make changes to the format. Any enhancements to the file format can be made only if Adobe decides to make them. Open-source formats such as Ajax do not have this limitation. In Adobe’s defense, the company has been making great efforts to distribute Flex as open-source to encourage community feedback and development. Because Flex applications are published as SWF files, there is a delay when loading them that isn’t an issue for regular HTML files. Depending on the client’s computer speed, the network connection, and the amount of data in the SWF file, the initial load delay can be several seconds. This is no different from any other thin client type of application such as a Java applet or even a regular desktop application, for that matter. The upside is that once the application loads, the user experience is very fast and smooth, without HTML’s frequent page reloads. The Apollo project removes many of Flex’s limitations but comes at the price of no longer being an Internet application. Apollo executes Flex applications within the context of a full-blown desktop application. Apollo consists of a set of runtimes that enable you to create stand-alone applications that run on Windows, Mac, and Linux. It allows you to have total control over the look of your applications and can use funky things such as transparency and non-rectangular windows. Essentially it’s taking Flex and creating a stand-alone application. Apollo has been renamed Adobe AIR, which integrates HTML, Ajax, Flash, and Flex all together into one desktop application. You’ll be an interactive guru if you learn Flash, Flex,


Chapter 1:

Flex Fundamentals

AIR, and ActionScript, which all enable you to build cooler applications. You can get more information about AIR here: http://labs.adobe.com/technologies/air.

Flex vs. HTML/Ajax In the beginning there was HTML, and it was good, but it’s made to generate static content. There’s no support for user interaction on a page. Animation is limited to animated GIF images. As with practically any other technology on the web there is constant pressure on developers to improve and add functionality to their web sites.

Dynamic HTML Dynamic HTML is the combination of HTML, style sheets, and a scripting language to animate or modify the appearance of a web page according to user actions. The first scripting language was JavaScript, introduced by Netscape. Unfortunately, the scripting language landscape resembles a war-torn battlefield. Microsoft responded to Netscape’s JavaScript by developing its scripting language, JScript. While similar to JavaScript, it’s not identical. This is the first landmine that anyone scripting a page to make it interactive must navigate.

DOMs To make matters worse, no one could agree on how to describe the elements of a web page, called the Document Object Model (DOM). Again, Netscape and Microsoft developed similar but not entirely compatible DOMs. The result is that the JavaScript written to modify objects on a page often needs to check which type of browser is in use and behave differently. This creates endless headaches for anyone writing code. The W3C, which develops web standards, stepped in and began defining standards for how a DOM should be defined and manipulated. This has helped make working with multiple browsers easier, as most modern browsers support at least one revision of the W3C DOM standard.

Ajax The combination of JavaScript and the DOM allows web developers to script out interactions on web pages. Ajax takes that one step further by allowing JavaScript to request additional information from a web server without a page request (and subsequent screen refresh). Figure 1-3 shows the distinction between the JavaScript engine and server-side scripting. Additionally, it displays the interaction of the Filesystem or Database and Apache or IIS, which both reside on the web server and the web browser.

13


14

Flex 3: A Beginner’s Guide

Figure 1-3 JavaScript and DOM interaction

Of course, you don’t necessarily have to choose between Ajax and Flex. A bridge framework already exists to call Flex code from within Ajax, so the two can be effectively used together. This framework, called the Flex-Ajax Bridge, is available from Adobe Labs: http://labs.adobe.com/wiki/index.php/Flex_Framework:FABridge.

Cross-Platform Support with Single Binary Unlike DHTML and Ajax, which are highly dependent on the browser’s environment, Flex is dependent on the Flash Player web browser plug-in. Therefore, it’s important to know how well supported the Flash Player plug-in is. The good news is that Adobe states that its market penetration is 98 percent for Flash Player version 7 and 83.4 percent for version 9 within mature markets. The same Flex-generated code works on each client regardless of the OS the browser is running on. This cannot be said of Ajax. It’s hard to even support the multitude of quirks between browsers on the same platform when developing in Ajax.

Flex Versions In order to build developer support, which is critical for the adoption of any new language, Macromedia and now Adobe have lowered the cost of the Flex line and made available free components. We’ll walk through the older Flex versions to give you some perspective


Chapter 1:

Flex Fundamentals

on how Flex was originally made available and the changes in features. Through the various releases there has been a consistent theme that if you need to do Enterprise-style data communication to a server, you’ll end up paying premium pricing for Flex.

Initial Releases The initial releases of Flex were called Flex Server 1.0 and 1.5. They were marketed principally to the enterprise market and had price tags to match. At $15,000 per CPU they were beyond the reach of most users. Free developer and trial editions were available with restrictions on their use. Version 1.5 was considered the first version ready for production use.

Adobe Flex 2.01 Adobe Flex 2.01 represented a major improvement to the Flex framework. Flex 2 supports ActionScript 3, compliant with the latest EMCAScript standard, for scripting page interactions. Flash Player version 9 is required to run Flex 2.0 applications. The product is available at three different price levels.

Flex 2 SDK Flex 2.01 is the current production version. It uses a licensing model that includes a free version of the SDK framework called “Flex 2 SDK.” The SDK includes the base code libraries and compiler. This is enough to develop Flex applications, but the next level up includes Flex Builder, which is more convenient to use.

Flex Builder For about $499 you can purchase the Flex Builder, which is a plug-in to develop Flex applications using the Open-sourced Eclipse IDE. The Eclipse IDE can be customized to work with a variety of programming languages. The plug-in allows for a high degree of integration between the IDE’s code development features and the Flex SDK.

Flex Data Services To enable your Flex clients to perform Enterprise communication such as talking to a database server or a Java-based server, you can optionally purchase Flex Data Services. This product runs on a back-end server and brokers advanced data communication. It also supports data synchronization, pushes communication to the client, and publishes-subscribes data updates.

NOTE You don’t need Flex Data Services to make database calls.

15


16

Flex 3: A Beginner’s Guide

Adobe Flex 3 Adobe Flex 3 is currently in public beta and available from the Adobe Labs web site (http://labs.adobe.com/technologies/flex/flexbuilder3). Its development code name is Moxie. Adobe has publicly committed to release many of the components of Flex to the open-source community (all components except Charting and Advanced DataGrid). As part of the Flex Beta 3 process, Adobe is providing access to its bug tracking database as well as frequent development builds. Flex 3 supports these new features: ●

Code refactoring supports the renaming of variables, classes, and methods. For example, changing a class name automatically updates all instances of the class.

The Adobe Integrated Runtime (AIR) framework supports building cross-OS rich Internet applications that can access local desktop resources.

Persistent caching reduces SWF file size.

The Advanced DataGrid improves upon the 2.0 DataGrid by adding hierarchical (tree) display of data, column grouping, custom rows, and other new features.

Memory and performance profilers aid production application tuning.

The Flex Data Services feature has been renamed to LiveCycle Data Services (LCDS). LCDS has the following new features: ●

Support for Ajax Data Services

PDF generation on the server

An improved SQL adapter that makes interacting with databases easier using Data Management Services

Overall better performance and reliability

The public beta is available for free downloads. Once the beta period is over, pricing is expected to be similar to Flex 2’s pricing structure.

How Flex Works The process to build a Flex application can be split up into four steps: 1. Design and Configure 2. Build


Chapter 1:

Flex Fundamentals

3. Deploy 4. Secure

We’ll walk through each of these steps.

Design and Configure The first step in designing any application is determining what you want the application to do. Once you’ve figured out what you want your application to do, you can begin to select which API functions to use in order to build your application. Selecting the right plan of attack can make the difference between an easy, clean implementation and a lot of extra work.

Build Building a Flex application consists of compiling and debugging. You may be able to squeak by without using the debuggers. It’s often possible to place code into your application to display important information if you’re having trouble getting your desired result, but we’ll show you how to use them just in case.

Compiling The compiling step creates the common binary SWF file that the Flash Player will use to execute your application. The binary file is created from your source files, including MXML, ActionScript, Runtime Shared Libraries (RSL), SWC (Shockwave Component), and media files such as images. The process is similar to the way Java files are compiled into a binary bytecode (the equivalent to the SWF file) that is then executed by the Java Runtime Environment (instead of the Flash Player for Flex). The two Flex compilers are mxmlc and compc. They can be configured and launched from either the Flex Builder environment or the command line. Options can be set for enabling debugging and setting the paths to search for your files. The compc compiler, also called the Component Compiler, is used to package components, classes, and other files together into an SWC or RSL file. The packaged file can then be included in your application when you compile with mxmlc, sometimes called the Application Compiler. The RSL is actually deployed as an .SWF file. There are a lot of acronyms that may cause you some confusion. An SWC file is more or less an archive of SWF files, assets, and some MXML that says how the pieces fit together. An SWC file can be expanded using a ZIP utility like PKZIP. RSL files allow you to put common code elements into a separate file, and then if you have multiple Flex applications on the same server, all of them can reference the code in your RSL file instead of including the code in each Flex application. This saves time and energy in the long run.

17


18

Flex 3: A Beginner’s Guide

The SWF file is the end product of the compilation process and once deployed will be available for end users to request from a web server and execute within their Flash Player. Just because your application compiles, that doesn’t mean it will work as expected, so it’s important to know how to debug it.

Debugging Your Application You may debug your application with any of these three debuggers. They include the Flash Player debugger, the Flex Builder debugger, and the Flex Command-Line debugger. The Flash Player debugger version differs from the standard Flash Player that end users use. It has additional functionality for catching errors and analyzing runtime problems but otherwise behaves like the Flash Player. The Flex Builder debugger is a full-featured debugging environment. It supports setting breakpoints, lines that you select in your code where execution stops and you can inspect the state of your program such as the values in variables. Once execution has paused, you can control how many statements to run before stopping again. This might mean jumping over a function, which executes the code within the function without stopping, or entering the function and stopping at each line. The last option is the Flex Command-Line debugger. It is also a full-featured debugger but uses a command-line interface. It has the advantage of being a stand-alone tool but is also harder to use, since there is no graphical interface. At this time the Flash Player debugger and the command-line debugger are free, but the Flex Builder debugger is part of the $499 Adobe purchase price. Of course, before anyone can use your application, you must deploy it to a publicly accessible web server.

Deploy To make your application accessible to end users, you must publish the SWF file on a web server. Typically there’s also some HTML code to integrate the SWF file with the rest of the page. End users will access the SWF file by having their web browser request the SWF file and launch the Flash plug-in to process it.

Assets In addition to the SWF file any assets that your Flex application uses must also be published. Assets include files such as images, video files, XML data files, and RSL files if your application uses them. You distribute a component as an RSL file by first creating the RSL using the compc tool. After that, use the library’s location added into the compiler when you compile your application. Library files include all files you need for the application you’re building. For example, lib compiles all of the classes under the src directory into an SWC file, and places that in the bin directory. All necessary dependencies are built in when creating the library SWC file.


Chapter 1:

Flex Fundamentals

Because a single SWF file may rely on several asset files when the client’s browser requests the SWF, all of the required asset files will also be requested. While deploying assets, you may need to take extra steps because of the Flash Player’s built-in security. We’ll touch on those in depth later on.

Flex Applications Web Integration Your Flex application is integrated into a web page as an SWF file. The web page may be simple HTML or a dynamically generated web page like a PHP, JSP, ASP, or ColdFusion page. This page is called the wrapper. It specifies where your Flex application appears on the web page and the filename of the SWF file. The wrapper page may be as simple as providing the minimal <object> and <embed> tags that specify the display characteristics of the Flex application and the SWF file location. The wrapper may also contain code to detect if a required version of the Flash Player is installed and redirect the user to a download page if it isn’t. Depending on which tool you use to develop your Flex application, the wrapper page may be created for you or you may need to create it yourself. If you’ve used the Flex Builder tool to create your Flex application, it will automatically generate a wrapper file for you when you compile your application. The file will be located in the bin directory of your project; you copy the relevant code from this file to your HTML file when you publish the SWF file. If you used the mxmlc command-line compiler to generate your SWF file, then you’ll also need to create the wrapper file. We’ll provide detailed instructions on how to do this later on. You can also add JavaScript to the wrapper file to communicate with your Flex application through user events in the web page such as clicking objects. Figure 1-4 displays the process that transforms your Flex source files into the final product: an SWF file that’s played in the client’s web browser.

Securing Your Application Security is such an important part of building web applications that it’s considered to be a part of the application creation process. This approach helps to avoid an application being built and deployed without analyzing security implications. There are two fronts on which we’ll battle security issues. The first front is the security features already built into the Flash Player. The second front is building code within the application that doesn’t open up any security holes. Because the Flash Player has always been built to run SWF files from arbitrary, non-trusted sources, its designers gave a great deal of thought to limiting security risks to the client computer. Again, the Flash Player is similar to the JavaScript processing built into the browser in that only certain functions are allowed.

19


20

Flex 3: A Beginner’s Guide

Figure 1-4 From Flex source to player

The Flash Player uses the concept of a sandbox to enforce security when executing SWF files. While code is allowed to run, it isn’t allowed to access the client’s file system. It’s also limited in the ability to connect to network resources (such as sending an e-mail). Beyond the security built into the Flash Player, you may also need to validate users using your own code. For example, the Flex application may access remote data that has sensitive information. You’ll need to take care to make sure throughout the development process that your security code adequately checks for user credentials without revealing unintended information. The Flash Player has the following built-in security features: ●

It executes code from an SWF within a sandbox environment.

Communication between a Flash application and a server is encrypted using SSL.

Only special objects called SharedObjects may read or write to the local drive. SharedObjects have their own restrictions and must be created in the same domain.

Data may be read only from servers in the same domain unless the server specifically allows another domain.

All of these features make the process of managing security easier for you. Next you’re going to install Flex and all associated files so you can start working with MXML and ActionScript to create an application, a gaming system, an online tutorial, or something else that you may fancy.


Chapter

2

Installation and Modules

21


22

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

Installing Flex

Flex Builder Projects

General Requirements for SDK

Downloading the SDK Installation

Apache/IIS Flex Module

W

e’re assuming you’ve installed software before, but have demonstrated how to install the various distributions of Flex in this chapter whether you are using Mac OS X, Windows, or a UNIX machine. Some parts of Flex are available for free, while some are only available by purchasing them. Just as MXML is a new language and way to design, Flex calls your projects workspaces. There are samples that you can run after you install, and we also get you ramped up with creating a test project and also testing your install. Overall this is a simple process of compatibilities, installation, running samples, and testing your install and a project.

Installing Flex In order to install Flex, download the file called Adobe Flex Builder 3.0 from www.adobe .com/support/flex. There are several package choices to choose from in order to install all the files necessary for your specific implementation of Flex. The differences about how the run-time builder works with either IIS or Apache are also discussed for your benefit. This book uses Flex Builder 3 stand-alone as the default installation method in most of the code examples, since it’s the easiest to use when starting out with Flex.

Flex Distributions Flex comes in three different base packages: ●

Flex Builder Distribution

Software Development Kit (SDK)


Chapter 2:

Installation and Modules

Apache Runtime Module We’re going to compare these distributions to figure out which one is right for you.

Flex Builder Distribution The Flex Builder distribution includes the SDK, so don’t install the SDK separately if you’re going this route. Flex Builder also includes an integrated development environment (IDE) built on Eclipse. Eclipse is an open-source IDE that is customizable through plug-ins that define behaviors for a particular language. There are many plug-ins available, particularly for developing Java applications. You can either download just the plug-in for Eclipse if you’ve already installed it, or you can download a combined Eclipse and Flex Builder distribution. Flex Builder’s advantages include: ●

The ease of use of a graphical user interface (GUI)

Integration with build tools such as Ant

Online help to assist you with writing your code

Automation of common tasks such as compiling and deploying

Code and file tree view browsing

The one downside to Flex Builder is that it’s not free. After the 30-day trial, you must purchase a license to continue using it. While portions of Flex are open source, there are portions that are not, and you’ll have to pay in order to use the enhanced functionality. Flex Builder is available for Windows and Mac OS X 10.4. There are hacks available for it to work with Eclipse on Linux as a plug-in, but they are not supported by Adobe.

Flex SDK The free Adobe Flex 3 SDK includes all the technologies you need to start building Flex applications immediately. The SDK includes MXML and ActionScript 3.0. Then there is the basic framework, which is a set of predefined class libraries and applications services that include layout and display systems to manage the user interface (UI), data binding, and style parameters. You’ll also get drag-and-drop management along with the effects and animation that control your transitions and the motions that go with them. Similar to Adobe Captivate you have components that help you create buttons, check boxes, and radio buttons all the way up to combo boxes, data grids, and rich text editors.

23


24

Flex 3: A Beginner’s Guide

The downloadable library comes with skins that you can restyle or even re-skin to match whatever look and feel you want your application to employ. At the heart of all this is the Flex framework itself, which takes MXML files and compiles them with your ActionScript ones and any other resources you’re using to build your dynamic application. The compiler comes as a stand-alone offering or as part of Flex Builder, allowing you to decide whether to develop in the Eclipse-based IDE or an IDE of your choice. However, the Flex SDK doesn’t support an IDE, which could create problems for new users. If you’re a seasoned developer who has created applications working directly with source code using the editors of your choice, then you can just download the Flex SDK.

Apache/IIS Runtime Module The Adobe Flex Runtime Module for IIS or Apache allows you to rapidly test your Flex application from source code alone. The compiler is built into the module that integrates with IIS or Apache Web Servers. To illustrate how the Flex Module fits into the web architecture, see Figure 2-1. To preview and test your code, all you need to do is place the source files on your web server within the appropriate directory and request the specific pages. This saves considerable time when developing and testing your applications. There are fewer steps to see if your code works as expected versus the traditionally accepted route of compiling

Figure 2-1 The relationship between the Flex Builder module and other web components


Chapter 2:

Installation and Modules

and then deploying the testing procedure. Additional advantages of using the Runtime Module include the following: ●

Error resolution is easier, as errors and warnings from the compiler display directly in the browser window.

It’s faster to preview changes, since you don’t have to manually compile your changed source files.

There’s no risk of forgetting to place the update SWF after compilation on your web server.

HTML files can point directly to MXML files, and the compiling happens automatically, ensuring the code used is the most up-to-date.

The downside to the Flex Runtime Module is that it’s slower than compiling as opposed to deploying; therefore, it’s not the best choice for deploying your applications to the world at large. It also doesn’t support Flex Data Services.

Installing Flex Builder Installing Flex Builder versions differ only slightly between Windows and Mac OS X, since they both rely on Eclipse and Java. The plug-in distribution also has a similar installation sequence that isn’t covered, since most users don’t already have Eclipse installed on their systems.

Windows The install screens you’ll see in this chapter are for a Windows 2000 installation; however, Windows XP and Vista screens look very similar. The JRE environment is included with this installer, so there is no need to download and install it separately. When installing, the stand-alone version of Flex Builder Eclipse should not be installed separately. Perform the following steps to install Flex Builder: 1. From the Adobe Labs web site (www.adobe.com/cfusion/entitlement/

index.cfm?e=labs_adobeflexbuilder3), select the Windows stand-alone installer. Download it to a specific directory or your desktop. 2. Double-click the installer file to start the install. The file should be named similar

to flexbuilder3_b3_win_sa_121207.exe.

25


26

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

3. The Introduction screen appears. Click Next. 4. The License Agreement screen appears. Accept the License Agreement by selecting the

radio button adjacent to I Accept The Terms Of The License Agreement and click Next. 5. The Choose Install Folder screen appears as seen in Figure 2-2. Accept the default of

C:\Program Files\Adobe\Flex Builder 3 by clicking Next. 6. The Flash Player Installation screen appears. Accept the default of installing Flash

Player 9 for Internet Explorer and Netscape/Firefox by verifying the check boxes are selected and clicking Next. 7. On the Pre-Install Summary screen click Install to commit to your choices and begin

installation. 8. After a few minutes of activity the Install Complete screen appears. Click Done to

close the installer.

Figure 2-2 Choose Install Folder screen


Chapter 2:

Installation and Modules

Figure 2-3 ColdFusion Installation Info screen 9. A ColdFusion Installation Info dialog appears, as seen in Figure 2-3. If you’re using

ColdFusion, click Yes and follow the prompts; otherwise, you can safely click No. Now that your installation is done, start Flex Builder: 1. Start Flex Builder by selecting Start | Programs | Adobe | Flex Builder 3 from the Start

menu, or for Windows XP, Start | All Programs | Adobe | Adobe Flex Builder 3.

NOTE Vista users must run Flex Builder as Admin the first time they launch it by right-clicking the Adobe Flex Builder 3 entry on the Start menu and selecting Run As Admin.

2. The Flex Builder Activation window appears. If you’ve already purchased Flex

Builder, enter the serial number now; otherwise, click Try. You should now see the Flex Development—Flex Start Page—Adobe Flex Builder 3.0 screen, similar to Figure 2-4.

27


28

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 2-4 The Flex Builder Start screen

Macintosh OS X If you are a Macintosh user with OS X, you need OS X version 10.4 or later in order for Flex Builder 3 to work. To install the Flex Builder stand-alone: 1. From the Adobe Labs web site (www.adobe.com/cfusion/entitlement/

index.cfm?e=labs_adobeflexbuilder3), select the Windows stand-alone installer. Download it to a specific directory or your desktop. 2. Double-click the installer file to start the install. The file should be named similar to

flexbuilder3_b1_mac_sa_061107.dmg. 3. The Introduction screen appears. Click Next. 4. The License Agreement screen appears. Accept the License Agreement by selecting the

radio button adjacent to I Accept The Terms Of The License Agreement and click Next.


Chapter 2:

Installation and Modules

5. The Choose Install Folder screen appears. Accept the default of inside Adobe Flex

Builder 3 in the folder Applications on the disk Macintosh HD by clicking Next. 6. The Flash Player Installation screen appears as shown in Figure 2-5. Accept the default

of installing Adobe Flash Player 9 For All Browsers by verifying the check boxes are selected and clicking Next. 7. After the Flash Player installs, the Pre-Installation screen appears. Click Install to

commit to your choices and begin installation. 8. After a few minutes of activity the Install Complete screen appears. Click Done to

close the installer. Now that installation is complete, start Flex Builder by launching it from the Mac OS X dock or double-clicking the Flex Builder 3 application icon in the Applications\Adobe Flex Builder 3 folder. The Flex Builder Activation window displays the first time you run Flex Builder. If youâ&#x20AC;&#x2122;ve already purchased Flex Builder, enter the serial number now; otherwise, click Try.

Figure 2-5 The Flash Player Installation screen

29


30

Flex 3: A Beginner’s Guide

After installation is complete, you’ll want to get started and build your first project. Projects are multifaceted, and we’ll begin by breaking down these concepts for you so that you get a good understanding of how everything fits together.

Flex Builder Projects Adobe Flex Builder uses the concept of projects to logically group the files and folders that an application uses within Flex Builder. While some of these concepts are relevant to developing with the SDK or the Flex Module, it’s principally Flex Builder that uses projects. A Flex Builder project contains additional information beyond your source files and media assets. Information such as how to build the files, where to deploy them, and how to debug them is also part of the project.

Workspaces Projects belong to a workspace, which is essentially the base directory where Flex Builder stores your files, including projects. You can have multiple workspaces, but you can only use one at a time, and moving projects between workspaces is a manual process. You can only select the workspace when starting Flex Builder. In order to create a new workspace, you’ll have to start over, since it isn’t recommended that you run two instances of Flex simultaneously.

Managing Projects in a Workspace The Navigator view in Flex Builder allows you to manage the resources associated with a project. The Navigator view is the top-left panel of the default Flex Builder layout. From the Navigator view you can add, remove, and import projects. You can also add and remove application files and resources that are members of projects. A workspace can have as many projects as you want. They all appear at the top level of the Navigator view. A project can also have more than one application. In order to create an application, you must first define a project to hold the application. When you create a new project in Flex Builder, it automatically creates an empty application. This application’s files begin with the name “main.” Which files are created automatically vary, depending on whether you’re creating an MXML project or an ActionScript project. They provide a starting point for developing your application. At this point you’ll continue to add code, resource files such as images, and other components to the project.


Chapter 2:

Try This

Installation and Modules

Creating a Test Project

To create your first project, do the following: 1. Launch Flex Builder. 2. To create a new Flex project, select New | Flex Project from Flex Builderâ&#x20AC;&#x2122;s File menu. 3. The New Flex Project window appears. Enter HelloWorld as the project name and

leave the default selection of None for the Server Type drop-down list as shown in Figure 2-6. Click Next. The Project name describes the purpose of your project and may not contain special characters or spaces. The Server Type specifies if the destination web server will process dynamic pages such as PHP or ASP.NET. Also, leave the Application Type

Figure 2-6 The New Flex Project dialog

(continued)

31


32

Flex 3: A Beginner’s Guide

set to Web Application. The Desktop Application option is for building Flex Adobe AIR applications, which are like Flex applications but run as true desktop applications. 4. The Server Configuration dialog appears as shown in Figure 2-7. This determines

where Flex will place your application when it is compiled. It must be a subdirectory of the project directory. To accept the default of bin, click Next. Other subdirectories can be selected by using the Browse button. 5. The New Flex Project dialog appears as shown in Figure 2-8. Click Finish after making

any of the following optional setting changes: ●

The Source Path tab allows selecting additional paths outside of the main source folder to search when compiling applications in the project. It may be left with the default of no additional paths.

The Main Source Folder where the source files reside by default can be modified from its default of src by clicking Browse.

Figure 2-7 The Server Type Configuration dialog


Chapter 2:

Installation and Modules

The Main Application File, which is the file that is run by default when the application is compiled and run, can be changed from the default that is based on the Project Name by clicking Browse.

The Output Folder URL optionally specifies where to publish the compiled application files.

To select additional libraries to include while compiling the project, click the Library Path tab. Projects, SWC folders, and SWC files can be added using the Add buttons along the right side of the tab. The Library path tab looks like Figure 2-9.

Figure 2-8 The New Flex Project Create A Flex Project dialog

(continued)

33


34

Flex 3: A Beginner’s Guide

Figure 2-9 The Library Path tab customizes the libraries and SWC files included at compile time.

You’re returned to the Main Flex Builder window, where there is a new entry in the Navigator pane for the new project you just created. Flex Builder automatically rebuilds your workspace. A default MXML block is placed in the HelloWorld.mxml tab as shown in Figure 2-10. It consists of the code: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> </mx:Application>

6. Modify the code in HelloWorld.mxml to match the following MXML code: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Panel paddingTop="15" paddingBottom="15" paddingLeft="15" paddingRight="15" title="Test Application"> <mx:Label text="Hello World!" fontWeight="bold" fontSize="20"/> </mx:Panel> </mx:Application>

This code should look familiar, since it’s similar to the code used in the Chapter 1 online Flex page demonstration. Your screen should now look like Figure 2-11.


Chapter 2:

Installation and Modules

Source pane Flex Navigator

Figure 2-10 The Flex Builder project with HelloWorld.mxml in the Source pane

Figure 2-11 The Hello World code

(continued)

35


36

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

NOTE The appearance of your screen may vary slightly as new releases of Flex Builder come out or if you are using Flex as an Eclipse plug-in with modified appearance settings.

7. To run your code, select Run Main from the Run menu. The Save And Launch dialog

displays as shown in Figure 2-12.

NOTE If you see a Run As dialog, select Flex Application and click OK.

8. Click OK to save your changes to HelloWorld.mxml. Unsaved changes must be saved

before you can run the code. Changes can be automatically saved by checking the Always Save Resources Before Launching check box. The application launches in your web browser as shown in Figure 2-13.

Figure 2-12 The Save And Launch dialog allows automatic saving of code when compiling and running.


Chapter 2:

Installation and Modules

Figure 2-13 The Hello World test application

As we mentioned, you’ll need to install the Flex SDK; however, there are variable elements involved with the installation, so we’ll talk about general requirements first.

General Requirements for the SDK Since the Flex SDK is built using Java you must have a modern version of the Java JRE installed to use the SDK. The required version varies based on your operating system. Table 2-1 shows the requirements for supported operating systems. If in doubt, note that Sun’s Java 1.5 is supported across the board for all OSs. OS

Required Java Version

Mac OS X v.10.4

Java 1.5 (default from Apple)

Windows 2000/XP/Vista

Java 1.4 (including IBM, BEA) or Java 1.5

Red Hat Enterprise Linux 3 or 4

Java 1.4 (including IBM, BEA) or Java 1.5

Table 2-1 Java Requirements for the Flex SDK

37


38

Flex 3: A Beginner’s Guide

Downloading the SDK Installation The Flex SDK can be downloaded for all major platforms from the following link: http://labs.adobe.com/technologies/flex/sdk/flex3sdk.html. Remember that Flex Builder is limited to Windows, Mac OS X, and limited support for Linux.

Removing the Flash Plug-in It may be necessary to remove your existing Flash Player Web plug-in to prevent conflicts with the Flash plug-in supplied with the Flex SDK. How this is accomplished depends on the way you originally installed it.

Linux Manual Removal If it was installed manually without using a package such as an RPM or DEB file, you can remove the SDK by deleting the libflashplayer.so binary and the flashplayer.xpt files in ~user_name/.mozilla/plugins/, where user_name is your username.

RPM Removal If you’re using a Red Hat–derived Linux, such as Fedora, then you’ll remove the plug-in like this: 1. As the super user (root) open a terminal. 2. Execute the rpm command by typing the following at the terminal prompt:

rpm -e flash-plugin 3. Click ENTER. 4. Follow any prompts. Accepting the defaults is OK.

The plug-in is removed.

DPKG Removal If you’re using a Debian-based Linux system, such as Ubuntu, follow these steps: 1. Open a terminal. 2. Execute the apt-get command by typing the following at the terminal prompt:

sudo apt-get remove flashplugin-nonfree 3. Click ENTER.


Chapter 2:

Installation and Modules

4. Enter the root user password if prompted for it. 5. Follow any prompts. Accepting the defaults is OK.

The plug-in is removed; you’re ready to have the SDK install its version of the plug-in.

Installing the Flex SDK You may be accustomed to using the package interface tool of your Linux installation to install software such as rpm or apt-get. Unfortunately, the Flex SDK packages are hard to find and generally not worth the trouble of building yourself. Therefore we’ll describe installing directly from the ZIP file. To install the Flex SDK, follow these steps: 1. The Flex SDK is distributed as a ZIP file. Download the ZIP file from Adobe Labs at

http://labs.adobe.com/technologies/flex/sdk/flex3sdk.html. 2. Download the platform-independent ZIP file. 3. Create a new directory of your choice for Flex, for example, /home/jon/flex_sdk. 4. Unzip the file you just downloaded in the directory you created. The SDK contains the

directories shown in Table 2-2. 5. Verify that the JDK ver 1.4.2_06 or later is installed and that your system path contains

the java_home/bin directory by entering java –version at the DOS prompt or Terminal for Mac and Linux. Figures 2-14 and 2-15 show the results for Windows and Linux. Ant

Flex Ant Tasks are used to automate the building of projects similar to a makefile for C programs.

Asdoc

Documentation files for the ASDoc tool. ASDoc creates HTML documentation from your Flex source code files.

Bin

Contains executables including mxmlc, compc, asdoc, and fdb. It also contains the Java configuration file jvm.config.

Frameworks

Contains support files for frameworks, including classes, configuration, and source code.

Lib

Java library support files.

Runtimes

Installers for Flash Player 9 and Adobe AIR.

Samples

Includes sample Flex applications.

Templates

Flash Player Detection HTML templates.

Table 2-2 Flex SDK Directory Structure

39


40

Flex 3: A Beginner’s Guide

Figure 2-14 The Java install verification on Windows

Notice that although the java command is executed on different operating systems, the command is the same and the output is similar. If the java command is not found, check your path. If the version is incorrect, you’ll need to install an updated JRE for your operating system. 6. Install the Flash Player supplied with Flex. It’s located in the runtimes/player/platform

directory. Platform indicates what OS you’re using, whether it’s Linux, Windows, or Mac OS X. For Windows the installer is an EXE file that must be executed. For Mac OS X the installer is in the standard DPG format. Linux users are supplied with a .tar.gz file that includes the library and a shell script to install the library.

NOTE It may be necessary to reboot your system after installing the Flash plug-in before using it.

7. Test your Flex installation by trying to run a sample application.

Figure 2-15 The Java install verification on Linux


Chapter 2:

Installation and Modules

Running Samples Once you’ve installed the Flex SDK, you’re ready to try out some of the sample applications that are included in the ZIP file. They must be compiled before you can run them. To compile all samples, execute the build script that is located in the samples directory where you installed the ZIP file. On Windows it’s called build-samples.bat. For everything else it’s called build-samples.sh. If you’d just like to compile a single application, you can do this manually by calling mxmlc on one of the MXML sample files. For example, to test the finder.mxml application, follow these instructions: 1. For Unix/Mac OS X open a terminal. For Windows open a command prompt. 2. At the prompt enter cd install_dir/samples/explorer.

The install_dir is where you installed the SDK. Enter build.bat for Windows or ./build.sh for Mac and Linux systems to build the explorer sample application. The application will build for about 5–10 minutes, depending on the speed of the computer. The build process looks like Figure 2-16.

Figure 2-16 The Explorer sample application building on Linux

41


42

Flex 3: A Beginner’s Guide

NOTE Over time Adobe may include a different set of sample applications with the SDK. If the explorer sample is no longer included, look for another sample and follow this process using that directory instead of explorer.

3. Transfer the resulting .SWF file to a web server or open it locally with a web browser

that has the Flash Player plug-in installed. For example, on Windows, if you installed the Flex SDK as C:/flex3dsk, use this URL in your browser: file:///C:/ flex3sdk/samples/explorer/explorer.html. You should see the sample application execute in your browser similar to Figure 2-17.

Apache/IIS Flex Module If you’re installing on your Windows or Mac OS X machine, it’s going to be easiest to install using the prebuilt installer. Let’s take a look at the requirements for the Flex Module.

Figure 2-17 The Explorer Flex sample displaying a ButtonBar component


Chapter 2:

Installation and Modules

Requirements Apache 1.x or 2.x is recommended on Windows, Mac OS X, or Linux. On Windows IIS versions 5.1, 6, or 7 may also be used. IIS 7 on Windows Vista may require installing additional OS components before running the Flex Module Installer. Specifically, the ISAPI Filter components for IIS and IIS 6 Scripting tools are not installed by default but are required. To install these components, do the following: 1. Open Turn Windows Features On And Off by selecting it from Control Panel |

Programs And Features. 2. Expand Internet Information Services. 3. Click the check box to enable IIS 6 Management Compatibility. 4. Expand Internet Information Services | World Wide Web Services | Application

Development Features. 5. Click the check box to enable ISAPI Filter Components for IIS.

Vista also requires you to add a MIME type mapping so that IIS allows access to .mxml files. From the IIS Manager select Default Web Site | MIME Types | Add.

Installer Download The Windows and Mac OS X versions of the installer can be downloaded either as stand-alone or bundled with the Sun JRE and the Flex SDK. If you’ve already installed the SDK and have the JRE, then download the non-bundled version. The following list shows the location for the download of Flex 3 at the time of publication. These paths will change over time, so you may need to start at www.adobelabs.com and select the download link. ●

Apache Module for Windows (EXE format) http://download.macromedia.com/pub/labs/flex/3/flex3compiler_b2_apache_win_ 100107.exe

ISS Web Server ISAPI Filter for Windows (EXE format) http://download.macromedia.com/pub/labs/flex/3/flex3compiler_b2_isapifilter_win_ 100107.exe

Apache Mac OS X (ZIP format) http://download.macromedia.com/pub/labs/flex/3/flex3compiler_b2_apache_mac_ 100107.zip

43


44

Flex 3: A Beginner’s Guide

Bundled Windows (EXE format) http://download.macromedia.com/pub/labs/flex_mod_apache/flex_mod_full_win_ 050107.exe

Apache Module for Linux and Other Platforms (ZIP format) http://download.macromedia.com/pub/labs/flex/3/flex3compiler_b2_apache_misc_ 100107.zip

Download the appropriate file and save it to a directory of your choice such as your desktop or home folder.

Installing Flex Module Windows/Mac OS X Installer To begin installation: 1. Execute the installer (for example, FlexMode.exe for Windows) you just downloaded

by double-clicking it or calling it from the command line. A language selection dialog appears like Figure 2-18. 2. Select English. The Introduction dialog appears. Click Next. 3. The License Agreement displays. Select the I Accept The Terms Of The License

Agreement check box and click Next. The Install Folder dialog displays. 4. Select a directory for the SDK to be installed, for example, C:/Program Files/flex_sdk.

Click Next. 5. The Apache Configuration dialog appears as in Figure 2-19. Select the installation

directory that holds the Apache configuration settings, usually C:\Program Files\Apache Software Foundation\Apache2.2\conf on Windows. Click Next.

Figure 2-18 The Language Selection dialog for the Flex Module


Chapter 2:

Installation and Modules

Figure 2-19 Apache Configuration Folder screen

6. The Web Server Location dialog appears. Select the web root, which is the directory

where web files are published. This is a directory like C:\Program Files\Apache Software Foundation\Apache2.2\htdocs. The installer will guess this directory based on the directory from the last step. Click Next to accept the path. 7. The Pre-Installation summary displays. Click Next to install the module. 8. The installer runs for several minutes. 9. Windows users may need to reboot their computer after installation completes.

The Flex module is now installed and ready to be tested.

Manual Flex Module Installation There is no pre-built installer for Linux, and itâ&#x20AC;&#x2122;s assumed that youâ&#x20AC;&#x2122;ve already downloaded and installed the JRE and Flex SDK version 2.0.1 or higher.

45


46

Flex 3: A Beginner’s Guide

Try This

Testing the Compiler Module

Perform the following steps to verify the installation worked for both manual and installer package installs. 1. Either reboot or restart your web server. 2. Copy a sample MXML file to the document root of your web server. On Windows with

Apache 2.2 this is C:\Program Files\Apache Software Foundation\Apache2.2\htdocs. On IIS it’s C:\inetpub\wwwroot. On Mac OS X it’s /Users/short_username/Sites/, where short_username is your short username. 3. Access the file from your web browser using the localhost address. For example, if

you placed the file sample.mxml into your webroot on Windows, you’d use the URL http://localhost/sample.mxml. 4. The module should automatically create an HTML wrapper to execute the embedded

SWF file complied from your MXML file. 5. To optionally debug your Flex application, simply add ?debug=true to the end of the

URL. For example, to debug the MXML file mentioned in Step 1, use http://localhost/ sample.mxml?debug=true.

In Chapter 3 we’ll introduce the principles of MXML and ActionScript along with information about basic programming functions such as variables, expression, functions, and methods.

Ask the Expert Q: A:

What should I do if I receive an error about not having a graphical display on my Linux system? If you receive this error, add the following line to your flex-config.xml file: <headless-server>true</headless-server>


Chapter

3

Getting Started

47


48

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

Principles of MXML

Principles of ActionScript

Variables

Expressions

Functions and Methods

Flow Control and Looping

Event Handlers

OOP

Methods

Understanding MXML Namespaces

W

hen you write a Flex application, you use a combination of MXML to declaratively set up the user interface and ActionScript to provide the logic that responds to user interactions. MXML is a derivation of XML, which is why it has inherited how to handle namespaces from XML. It all boils down to needing namespaces for your files. ActionScript is derived from JavaScript, so if you use either of these languages, you’ll have no problem jumping right in and understanding what Flex is trying to accomplish. ActionScript uses variables, and they’re referenced by their names when you’re writing your program. ActionScript can pick your data type for you, with the most common ones being numbers, strings, and Booleans. It can also auto-modify your variable, but this could make code debugging more complicated for you. Then there are expressions, which evaluate to a single number, a Boolean value, or an object; however, expressions aren’t limited to variables; they could contain functions, numbers, or anything that results in a single value. The manifest file tells the Flex compiler how to find ActionScript code that corresponds to MXML tags in namespaces.


Chapter 3:

Getting Started

Functions group code together and take parameters and then return an optional single value, while methods are another name for a function if it’s part of a class. Names for functions and variables have similar constraints, because some words and characters cannot be used. Then there is program flow and looping, which define what steps your program follows by using statements such as IfElseThen or switch. Looping uses either for or while. Object-oriented programming (OOP) is an important part of the Flex framework. ActionScript uses similar types of keywords such as class and concepts just as Java does for helping with OOP implementation. Special OOP keywords such as class and extends help define your classes. A great feature of OOP is its ability to inherit the properties and methods of classes. Then there are static and non-static variables that are used with classes. But methods are defined within a class. Instantiation is where an object is created based on a class. All of these concepts may be familiar to you at this point, but we’ll go over them in greater detail.

Principles of MXML As we discussed in Chapter 1, MXML and ActionScript are used hand-in-hand to create Rich Internet Applications. We’re going to go more in depth in this chapter, since you already have the basics of MXML. Some common practices in language syntax are used, such as the use of curly braces ({}) to force your application to evaluate an expression. Just so you understand expressions, when you evaluate one, it can be a mathematical expression that has a variable as part of the expression. For example, if x=5, the expression 2 + 4x becomes 2 + 4 * 5, which is equal to 2 + 20 or 22. To evaluate an expression with a variable, simply substitute the value of the variable into the expression. MXML is used with Flex Server and is dynamically compiled into standard binary SWF files. However, Adobe’s Flex Builder IDE and Flex SDK can also generate SWF files from MXML for you to use without having the Flex Server. If you know HTML, then MXML should be fairly easy to understand, since they’re so similar. MXML is an XML-based markup language; it has a more structured and less ambiguous syntax than HTML and includes more tags than HTML. For example, DataGrid, Tree, TabNavigator, Accordion, and Menu are all some of the standard sets of tags. You can also extend MXML tags and create your own components. But the most significant difference is that the Flash Player, which enables your users to have an interactive experience with your web site as opposed to a static HTML-based page, renders MXML-defined user interfaces. You can also hand-code MXML using an IDE, such as Eclipse or Intellij.

49


50

Flex 3: A Beginner’s Guide

XML XML stands for Extensible Markup Language: a general-purpose markup language, just like HTML, but more restrictive. Standard Generalized Markup Language, or SGML, was the precursor to XML; hence, XML is a simpler way to code but is a subset of SGML. There are two levels of correctness for an XML document: ●

Well-formed If your document is formed correctly, it conforms to XML’s syntax rules. For example, if an element has an opening tag with no closing tag and isn’t self-closing, it’s not well-formed. This then means that a conforming parser isn’t allowed to process the document.

Valid A valid document also conforms to some semantic rules. These are either user-defined or included as an XML schema or DTD. As in the well-formed definition, if a document contains an undefined tag, then it’s not valid and a validating parser can’t process it.

Since HTML and XML have proved that they are easy to use and can create user applications, MXML piggybacked on this success and is really just a derivation of XML.

Principles of ActionScript Just as MXML is derived from XML, ActionScript is a scripting language based on a derivation of JavaScript. So, if you already know XML and some JavaScript, half the battle is already won; you’ll ramp up fast with Flex’s languages. ActionScript was initially designed for controlling simple 2-D vector animations created in Flash. But ActionScript was given more functionality as Flash grew, and more current versions allow for the creation of web-based games and Internet applications with the accompaniment of audio and video. As you’ll see in the ActionScript timeline, it’s gone through some serious re-working to make it a robust language. There were limited interactivity features in the first three versions of Flash, which meant that ActionScript was limited to attaching a single command to a frame or button. Then there were also constraints on basic navigation, which only allowed for simplistic controls, for example: ●

Play

Stop

Get URL

Goto


Chapter 3:

Getting Started

ActionScript Timeline In the Flash 4.0 iteration that was released in 1999, a small scripting language was born allowing for the inclusion of variables, expressions, operators, if statements, and loops. ActionScript was not referred to in the Flash 4.0 User Manual; it was described as “actions.” But technically, ActionScript was finally coming into its own and growing robust and more complicated.

2000–2003 ActionScript 1.0 was released with Flash 5.0 in September 2000; the actions from Flash 4.0 were enhanced again and finally named ActionScript. JavaScript and ECMA-262 influenced ActionScript in this release, supporting the standard’s object model and many of the core data types. Here local variables can be declared with the var statement, and functions you can define with parameter passing and return values are added to this release. A good change was that ActionScript could be typed with a text editor instead of being assembled by choosing actions from drop-down lists and dialog controls. When Flash MX and Flash Player 6 were released, the language remained mostly unchanged, with some minor changes, including the addition of the switch statement and the strict equality (= = =) operator, which is three equal signs. In this release you were allowed to create a loose type system and prototype-based inheritance. Loose typing is the ability of a variable to hold any type of data. This allows for rapid script development and is great for small-scale scripting projects. Prototype-based inheritance is the ActionScript 1.0 mechanism for reusing code and OO programming. For example, instead of a class keyword that defines common class characteristics, a special object that serves as a prototype for a class of objects is used. All common characteristics of a class are defined in the class’ prototype object, and every instance of that class contains a link to that prototype object. 2003–2006 ActionScript 2.0 was presented in September 2003 with the release of Flash MX 2004 and Flash Player 7. There was a demand for a language that could handle larger and more complex applications. Therefore, ActionScript 2.0 featured compile-time type checking and class-based syntax, using the keywords class and extends, for example. In this release you could constrain variables to a specific type by adding a type annotation so that type mismatch errors could be found when you compiled. Class-based inheritance syntax was introduced so that you could create classes and interfaces, similar to how they are in Java and C++. 2006–Today ActionScript 3.0 debuted with Adobe Flex 2.0 and Flash Player 9 in June 2006. ActionScript 3.0 was given an overhaul at this point, using virtual machines. Flash

51


52

Flex 3: A Beginner’s Guide

Player 9 has two virtual machines, AVM1 for code written in ActionScript 1.0 and 2.0, and AVM2 for content written in ActionScript 3.0. ActionScript 3.0 provides not only a significant enhancement in performance, but also a more robust programming model that lends itself to complex RIA development. RIA is the new buzzword in technological circles, and to meet that demand ActionScript 3.0 provided what was needed to create RIAs. The update to the language introduced several new features, which made it more robust: ●

Compile-time and runtime type checking—type information exists at both compile-time and runtime

Improved performance from a class-based inheritance system that was separate from the prototype-based inheritance system

Support for packages, namespaces, and regular expressions

Compilation to an entirely new type of bytecode, incompatible with ActionScript 1.0 and 2.0 bytecode

A revised Flash Player organized into packages

Unified event handling system that is based on the DOM event handling standard

Integration of ECMAScript for XML (E4X) for the purpose of XML processing

Direct access to the Flash runtime display list for complete control of what gets displayed at runtime

A completely conforming implementation of the ECMAScript Fourth Edition Draft specification

Backward compatibility

Proper Syntax Listing 3-1 is an example of using ActionScript when developing Flex applications, again presuming the following content to be in a file named text_slide.mxml: Listing 3-1 Create a textslide.mxml file <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" horizontalAlign="left"> Start of ActionScript code block <mx:Script> <![CDATA[


Chapter 3:

Getting Started

53

import mx.events.SliderEvent; import mx.controls.sliderClasses.Slider; private function sliderChange(event:SliderEvent):void { var currentSlider:Slider=Slider(event.currentTarget); textLive.text=String(currentSlider.value); Modify the TextArea text to be the current textLive.x=Number(currentSlider.value); value of the slider. } ]]> </mx:Script>

End of ActionScript code block

Applies the slider value to the X position of the TextArea

<mx:HSlider liveDragging="true" minimum="20" maximum="100" Links the change event to our change="sliderChange(event);"/> custom ActionScript function <mx:TextArea id="textLive"/> called sliderChange </mx:Application>

Notice that the <mx:Script> and </mx:Script> tags are used to mark the start and end of where youâ&#x20AC;&#x2122;re including ActionScript within the MXML file. When this code runs from Flex Builder, the default browser launches and displays the Flex application that looks similar to Figure 3-1. As you move the slider, the position of the slider displays in the text box and the text box moves out from the left of the screen based on the same value.

Figure 3-1 The Text Slider application launched in the Firefox browser


54

Flex 3: A Beginner’s Guide

Variables ActionScript uses variables to temporarily store information when running your program. Variables remember the last value you set. You can change the value as often as you want without posing any problems to the integrity of your data. There are several standard data types of variable values, including numbers, strings, arrays, and objects. Objects are a special data type that can hold multiple pieces of data in a predefined format. Variable values can be set when you write your code or be based on runtime values when your program executes, like the distance of the cursor from the left side of the screen. Creating and declaring a variable are the same thing.

Declaring Variables are referenced by their names. You select the name of the variable when writing your program. It’s best to select a name that represents the value stored by the variable, since this makes your code much easier to understand when you read it later or someone else looks at it. The name of the variable is set when you declare it. You can declare a variable with or without a value. Variables are declared and set with a statement such as this: var variable_name = value;

Notice that unlike many programming languages JavaScript doesn’t prefix its variable names with a dollar sign ($). For example, to create a variable called sample_text and set its value to testing, the example would be similar to this: var sample_text = 'testing';

The string value testing is assigned to the variable sample_text. Strings are a data type that store text. The semicolon at the end of the line alerts ActionScript that this is the end of the statement. While your code may still run if you forget a semicolon, it’s good practice to use them. There are also some naming conventions with variables.

Naming Variable names cannot contain spaces, but underscores are often used instead to split up words in a variable name. Variables cannot be the same as reserved words, which are ActionScript keywords such as for, while, and if.

CAUTION Beware that ActionScript is case sensitive, so sample_text is a different variable than Sample_Text.


Chapter 3:

Getting Started

As mentioned, variables store different types of information. There are several types that we discuss next.

Types You can either let ActionScript pick the type of data based on the value you’re assigning or you can specify the type explicitly. The type of information that a variable stores is important because it determines what operations are appropriate to perform on that variable. For example, you wouldn’t multiply a name (string) by a number, but it’s perfectly reasonable to multiply two numbers together. The most basic data types are numbers, strings, and Booleans. We’ll go through examples of numbers, strings, and Booleans.

Numbers Numbers obviously store numeric values. They can be used with the usual mathematical operations. For example, you might store a value such as the distance of an object from the top of the screen in a variable called y_distance like this: var y_distance = 400;

If you wanted to calculate the bottom of an object and the object’s height is stored in object_height, you could calculate it like this: var object_bottom = object_height + y_distance;

The variable object_bottom contains a number that represents the location of the bottom of the object on the screen.

Strings Strings in ActionScript are composed of one or more characters stored in order. They typically hold values such as names. While they can’t be used in mathematical operations, they do have their own functions such as concatenation, which glues two strings together. Strings are defined by using either a pair of single quotes (‘) or double quotes (“) to mark the beginning of a string and its end. For example, these two statements both assign the value strawberry to fruit. var fruit = "strawberry"; var fruit = 'strawberry';

The quotes are important; otherwise, ActionScript interprets the statement as assigning the value of the variable strawberry to fruit. Sometimes a string can look like another data

55


56

Flex 3: A Beginner’s Guide

type, but it’s important to realize it’s still a string. For example, let’s assign the value 20 as a string. var test = '20';

Although the value 20 looks like a number, it’s actually stored as a string in this example. If we go ahead and concatenate another string to this variable, it won’t be added, as you can see in this concat example. var test_concat = test + '40';

The variable test contains the string 2040, not the mathematical value of 60, as it would if the data type were numeric. Note that the plus (+) operator behaves differently on strings, as it concatenates instead of adding values.

Booleans Boolean values can represent only two values, true or false. Boolean variables are frequently used within conditional statements that determine the flow of your program, such as an if statement or loops, which we’ll discuss shortly. Booleans can be used with logical operations such as the keywords and, or, and not. For example, let’s create a Boolean variable called display_object and set its value to true. var display_object = true;

NOTE True and false must be lowercase.

Modifying Variable Types ActionScript allows you to change the type of variable and even does automatic conversions for you. For example, if you assign a string to a variable and then add a number to it, ActionScript automatically converts the number to a string and performs a concatenation of the two strings instead of returning an error. Unfortunately, the ease of type switching can make debugging your code difficult if you accidentally add the string and numeric values. Likewise, you can reassign a variable to hold a value of a different type without causing an error. Take for example this error code: var error = "critical"; error = 9;

ActionScript also supports Strict Data Typing to enforce data type rules.


Chapter 3:

Getting Started

Strict Data Typing Strict data typing is supported in every version of ActionScript after 1.0. It also allows you to explicitly specify the variable’s data type. Any attempts to assign a different data type to that variable cause a Type Mismatch error at runtime. To create or assign a strict data type variable, you’ll need to add a colon (:) and the data type after the variable name. The statement must also begin with the var keyword, which we’ll discuss shortly. For example, to assign an error to 1 as a number: var error:Number = 1;

Strict typing can also be applied to the values a function returns using the same colon (:) type notation. Now that we’ve covered variables, let’s jump into expressions.

Expressions Expressions are combinations of variables and operators that evaluate to a single value such as a number, a Boolean value, or an object. For example, the following statement contains an expression: var object_bottom:Number = object_height + y_distance;

The expression is the part to the right of the equal (=) sign that evaluates to the sum of object_height and y_distance. If those variables contain the values 2 and 4 respectively, the expression evaluates to 6. Expressions aren’t limited to just variables; they can contain functions, numbers, and anything that results in a single value. Expressions are very useful for many tasks, including assigning variables and determining program flow when used as part of a conditional statement. An example of using a function in an expression is var sqr_root:Number = Math.sqrt(4);

The expression uses the square root mathematical function to evaluate to the square root of 4, which is 2. Expressions form one of the building blocks for taking simple operations and gluing them together to make useful applications. They allow your programs to make decisions based on dynamic data instead of working with only predetermined values.

Functions and Methods Functions are an organizational tool for grouping code together that performs an action as a whole. They take parameters and return an optional single value. Functions prevent having to retype and maintain segments of code that you use more than once in addition

57


58

Flex 3: A Beginner’s Guide

to organizing your code. Without functions your code would have to be in a long list like the old school programming language BASIC. Once you accumulate more than a few lines of code, this quickly becomes unmanageable. Functions can take zero (0) or more parameters. In addition to grouping related lines of code that perform an action together, functions handle all the execution of the code, to be deferred until the time that your main code calls the function. Methods are simply another name for a function when it’s part of a class, another tool for organizing your code. While functions are used with procedural programming, methods are associated with object-oriented programming, which includes classes. While ActionScript is principally an object-oriented programming language, it still makes heavy use of functions, so you’ll really need to understand both models.

Defining Just like variables, functions must be defined before you can use them. Functions in ActionScript can be defined as either named or anonymous functions.

Testing Output In Flex Builder ActionScript, code is usually called from an MXML file. To show how the rest of the example code works, start with a common MXML file to display results of the ActionScript code. Create a new MXML application file in your Flex Builder project called display.mxml. This file will create an MXML textArea component and add the links to call the ActionScript code to define what string the textArea displays. Paste the following code into the source view: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete = "initApp()"> <mx:Script> <![CDATA[ private var theResults:ASResults = new ASResults(); public function initApp():void { displayText.text = theResults.calculateString(); } ]]> </mx:Script> <mx:TextArea x="10" y="10" id="displayText"/> </mx:Application>


Chapter 3:

Getting Started

The MXML file relies on a new ActionScript file called ASResults to define the code that does the ActionScript calculations. Create a new ActionScript file in the same project and paste in the following code: // ActionScript file package { public class ASResults { public function calculateString():String { var greeting:String; greeting = "Hello World!"; return String(greeting); } } }

After you select Display from the Run menu, you should see a browser window like Figure 3-2. At this point don’t worry about the class definition; it will be discussed later in this chapter.

Named Functions A named function is just what it sounds like: you’re creating a function and giving it a name all at the same time. Function names follow similar rules to naming variables. It’s good to name the function so that it indicates the general purpose of the function. Also,

Figure 3-2 The results of the calculations display in the TextArea

59


60

Flex 3: A Beginner’s Guide

functions cannot be named using reserved words, spaces, or unfriendly characters like @#%$*!. Function declarations start with the keyword function and then the name of the function followed by a list of parameters, if any. Lastly, the actual function code is enclosed by curly ({}) brackets. For example, the following code defines functions called calculateString and say_hello: public function calculateString():String { var numy:String; numy = "2"; return String(numy); } function say_hello(name:String){ return('Hello ' + name); }

If a function is defined with parameters, it can perform different actions based on the values passed into the function when it’s called. If your function only has one statement to execute, then the brackets are optional, but it tends to make the code easier to read and maintain to just always use the brackets when defining a function regardless of the number of statements. To have your function return a value, use the return keyword like this function example: function squared (x:Number){ return (x * x); }

The anonymous functions work like named functions, but they’re defined differently.

NOTE The rest of these examples assume that the ActionScript code is placed within the calculateString function definition.

Anonymous Functions An anonymous function definition looks like a mix between defining a function and setting a variable, for example: var say_hello = function (name:String){ return('Hello ' + name); }


Chapter 3:

Getting Started

Anonymous functions must be defined before they can be executed. If you’re using an anonymous function, it’s important to place its definition before any calls to the function. Named functions don’t have this requirement, as they are automatically available in a file.

Flow Control and Looping Building on the power of variables, expressions, and functions, the last major language features are program flow control and looping. These constructs define what your program does next based on criteria that you specify with variables and expressions. If you’ve used Flash, you’re already familiar with modifying the program timeline by using commands such as gotoAndPlay() on movie objects. ActionScript supports several control structures from looping to if statements, which provide complete control of how your code executes at runtime. The first type of flow control to investigate is the If statement.

If Statement The If statement is formally known as an If Then Else statement, as the else and else if portions are optional. It allows the program execution to branch based on the evaluation condition you specify. Its syntax is if (expression) then { //perform this block of code } else if (expression) { //perform this block of code } else { //the default block of code to execute }

The If Then Else statement builds on the concept of expressions. Each portion of the statement takes an expression within parentheses to determine if that block of code should execute or processing should move forward. Remember that you can build expressions to be as simple or as complex as you wish when deciding how your program executes. If you recall, all expressions eventually evaluate to either true or false, which means that the If Then Else statement checks for a Boolean value when evaluating the conditions. A simple example of an if statement: if (object_height > 100) { return("That's a tall object."); }

This example only returns the text “That’s a tall object.” if the value stored in object_height is greater than 100.

61


62

Flex 3: A Beginner’s Guide

Switch Statement A switch statement is useful for checking an expression that may have one of many values. While you can do this with an if/else statement or multiple if statements, it becomes tedious quickly. The switch statement executes the block of code from a case that matches the value of the expression specified after the switch keyword. Then, within curly brackets, each potential value to check for is listed after case keywords. The code to execute for each case is listed on the following lines up to the next case statement or the end of the switch statement. The break keyword is used to jump out of the switch if a match was found. Without the break keyword, all statements execute to the end of the switch after a matching case has been found. Listing 3-2 performs different actions based on a weekday variable. Listing 3-2 Weekday variables switch (week_day) { case "Monday": trace("yawn"); This stops program execution from also executing the rest of the cases. break; case "Tuesday": trace("not another status meeting"); break; case "Wednesday": trace("halfway there"); break; case "Friday": trace("TGIF"); break; case "Saturday": case "Sunday": trace("weekend!"); break; This is a catch-all if none of the other cases match. default: return("oops!"); }

The preceding switch statement displays different text for all days except Saturday and Sunday, as Saturday falls through to Sunday. The last nice thing a switch statement can do is to provide a default if none of the cases match. This example says “oops!” if the value of week_day doesn’t match any of the cases.


Chapter 3:

Getting Started

Looping The if statement is only one type of program flow construct. It’s often useful to execute a chunk of code until a condition is satisfied, and this is known as looping. There are two types of looping: ●

While

For

While Loop One type of looping supported by ActionScript is the while loop. The while loop executes its block of code until the while condition is false. Its syntax is while (expression) { //execute this code block }

The code within the while block executes until the expression evaluates to false. Therefore you must be careful not to write a while loop that doesn’t effect the expression, as this could cause your while loop to run forever, in what is known as an infinite loop. The Flash plug-in detects infinite loops and then errors out after a timeout, but it’s still poor coding and should be avoided. The following is an example of a while loop produced by replacing the code in ASResults.as. // ActionScript file package { public class ASResults { public function calculateString():String { var numx:Number=1; var numy:Number=1; var numrest:String; while (numx <= 5) { numy = numy * numx; numx = numx + 1; } return 'factorial: ' + String(numy); } } }

63


64

Flex 3: A Beginner’s Guide

Figure 3-3 The factorial of 5

This while loop calculates the factorial of 5 by calculating 1*2*3*4*5. The output of running the loop displays similar to Figure 3-3. The next loop makes counting, sometimes called iterating, and looping easier by providing syntax to do both at the same time.

For Loop The For Loop iterates through a range of values that you specify in its parameters. You can access the variable with the current value of the iteration in the code block that repeats. It’s possible to rewrite the last example using a for loop like this: Initialize statement

Iterate statement

var y:Number=1; for (var x:Number = 1;x <= 5; x++) { y = y * x; Stop condition } return('factorial: ' + String(y));

The For Loop in this example is taking three sections separated by the semicolon (;). They are as follows: ●

The initialize statement either sets the initial value of the variable or creates and sets that value. In this example x is created and initialized to 1 by the var x:number = 1 statement.

The stop condition is the next segment and must use an expression that includes a condition that’s modified by the loop or by incrementing the iteration variable so that


Chapter 3:

Getting Started

the loop isnâ&#x20AC;&#x2122;t infinite. In this example the code x <= 5 means the loop stops executing when the value of 5 is reached. â&#x2014;?

The last segment modifies the value of the variable to iterate. In this example x++ is a shorthand notation for x = x + 1, which adds 1 to x each time the loop executes. The output of running the loop is

factorial: 120

Event Handlers Another type of flow control that you need to know about is event handlers. Event handlers define a block of code to execute based on certain events. Events can include error conditions or user-initiated actions such as a mouse click.

Try This

Create an Event Handler That Displays an Alert

1. Launch Flex Builder. 2. Create a new MXML application called click_event.mxml. 3. Copy the text from the example that follows to define a button and event handler: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" horizontalAlign="left"> <mx:Script> <![CDATA[ import mx.controls.Alert; Includes the ActionScript code to draw

the Alert() dialog function initApp():void { button1.addEventListener(MouseEvent.CLICK, customEventHandler); } function customEventHandler(event:Event):void { Alert.show("The mouse was clicked."); } ]]> </mx:Script> <mx:Button id="button1" label="Click To Test Here" click="customEventHandler(event)"/> Shortcut for linking </mx:Application> the click event to the

custom event handler

4. Select Run click_event from the Run menu.

Defines the button to click

65


66

Flex 3: A Beginner’s Guide

Figure 3-4 The Flex application before clicking the button 5. Save the file if prompted. 6. The application displays in your default web browser.

You’ve created a button with an ID of button1. It then assigns a custom event handler to execute on the mouse click event for that button. The custom function simply displays some text in response to that event. It’s also possible to specify event handlers when creating objects using MXML by specifying the event and the function to execute within the object’s MXML definition. Figure 3-4 show how the Flex application looks in the browser before clicking the button. After clicking with the mouse, the screen looks like Figure 3-5. The button is now shaded, and an OK button appears.

Figure 3-5 The application in the browser after clicking the button


Chapter 3:

Getting Started

MXML Conversion Remember that your MXML code is converted into ActionScript when your Flex application is compiled into an SWF file. It’s therefore incredibly useful to understand the basics of ActionScript, including flow control. The if and switch statements help you branch the flow of your program, since For and While loops make repeating the execution of a block of code easy. The last hurtle to working with ActionScript is to understand the concepts of object-oriented programming.

OOP One of the most challenging aspects to pick up with Flex is the object-oriented programming nature of the Flex framework. ActionScript supports both procedural-style programming and OOP. While OOP takes some effort to understand, it also promotes much more flexibility and extensibility when developing applications. As Flex and ActionScript have evolved, their OOP implementation has improved and is now easier to learn and use than ever, so don’t worry! If you’ve worked with classes and objects in another programming language such as Java, you’ll be happy to know that ActionScript uses many of the same keywords and concepts.

Encapsulation One of the major benefits of using OOP programming is encapsulation. Encapsulation is similar to the process of putting your code into functions to make it easier to reuse and organize, but takes it one step further by creating a clear boundary between existing code and new code that you create. You no longer have to worry that making a change in your code will break existing code that you use elsewhere. It provides a way to group multiple methods together logically, making your code easier to understand and write.

Classes Since ActionScript is based on the same ECMA standard as JavaScript, it implements OOP in the same way as JavaScript. Older versions of ActionScript didn’t directly support classes but used a function object where you could create class-like objects. Since ActionScript 3.0 is standard today, that’s how classes will be created in the examples. Special OOP-related keywords like class and extends help define your classes. When working with classes, it’s important to know some of the other terminology, including constructors and prototypes. A constructor is a special method for a class that is called when you request an instance of a class. A prototype is a special holding area for the properties and methods than any derived object will also inherit.

67


68

Flex 3: A Beginner’s Guide

Packages Packages provide a way of grouping classes together with a common name. Use the package statement when declaring a class to make it part of a package. For example, to create a class called InitTest as part of the test.weekly package: package test.weekly { public class InitTest {} }

Access Attributes When defining classes, you can use one of the keywords in Table 3-1 to define where the class is modifiable relative to the package it’s defined in, as the table demonstrates. If you don’t specify an attribute when creating a class, the default is internal. For example, to create a final class called Concrete: final class Concrete {}

Body To create a class, use the class keyword followed by the name of the class. Your class definition is enclosed by curly ({}) brackets. It contains all of the attribute and method declarations for your class. For example, you can define a simple class that holds a few properties and a method like this: public class MyTextClass { public var height:Number = 100; public var width:Number = 200; public var text:String = "myText"; public function showText():String { return text; } }

Class Attribute

Meaning

Dynamic

Properties can be added at runtime.

Final

Cannot be extended.

Internal

Visible to the current package.

Public

No restrictions.

Table 3-1 Class Attributes


Chapter 3:

Getting Started

You can also define a namespace inside a class body. The following example shows how a namespace can be defined within a class body and used as an attribute of a method in that class: public class SampleClass { public namespace sampleNamespace; sampleNamespace function doSomething():void; }

Static Variables Just like variables that are defined outside of classes, static variables can be defined using the const or var keywords. If a variable is defined using const, its value cannot change. A class property has the static keyword before its definition to make it static. Static variables are associated with the class instead of the instance, so theyâ&#x20AC;&#x2122;re values that can be shared with any number of class instances. This provides an easy way of keeping track of totals between your objects. For example, to modify MyTextClass to track how many total instances of this class have been instantiated, use Listing 3-3. Listing 3-3 showTotalTexts() package { public class MyTextClass { private static var totalTexts:int = 0; public var height:Number = 100; public var width:Number = 200; public var text:String = "myText"; public function MyTextClass() { totalTexts = totalTexts + 1; } public function showText():String { return text; } public function showTotalTexts():String { return (String(totalTexts)); } } }

Outside of the class the totalTexts property can only be accessed by referencing the function showTotalTexts() similar to Listing 3-4.

69


70

Flex 3: A Beginner’s Guide

Listing 3-4 showTotalTexts() <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete = "initApp()"> <mx:Script> <![CDATA[ public var MyTestAlternate:MyTextClass = new MyTextClass(); public var MyTest:MyTextClass = new MyTextClass(); public function initApp():void { displayText.text = MyTest.showTotalTexts(); } ]]> </mx:Script> <mx:TextArea x="10" y="10" id="displayText"/> </mx:Application>

It’s not allowed to access a static variable within an instance of the class such as: displayText.text = MyTextClass.totalTexts;

NOTE If a variable is declared as both static and const, then it must also be defined in the class definition.

Instance Variables An instance variable is a non-static class variable. The variable’s value is unique to whichever instance of the class has been instantiated. This is useful for tracking data that is relevant to current instance such as the screen coordinates of an object, as you wouldn’t want to store that information at the class level. A subclass cannot override a class’ instance variables.

Methods Methods are functions defined within a class. Unlike functions, they can only be called within the context of the class instance from which they are created.

Defining To create a method within a class, use the function keyword. For example, to create a test method: public function testFunction() : Number {}


Chapter 3:

Getting Started

Or you can assign it using the anonymous function syntax: public var testFunction:Function = function () : Number { return (2)}

This syntax isn’t considered a best practice unless you’re attaching an anonymous function to a prototype object.

Constructors Constructors are special methods that are called when instantiating a new instance of an object. They are named the same as their class name. Constructors can call return(), which would usually return a value, but they cannot return a value.

NOTE Do not define a return type for your constructor, not even void.

For example, to initialize the text property of the MyTextClass object, create an ActionScript file in your project called MyTextClass.as. package { public class MyTextClass { public var text:String = "myText"; public function MyTextClass(){ text = "John"; } } }

Since this function has the same name as the class, it is the constructor.

Change the display.mxml file in the project to contain this code in the Source view: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete = "initApp()"> <mx:Script> <![CDATA[ var MyTest:MyTextClass = new MyTextClass(); public function initApp():void { displayText.text = MyTest.text; References the value that was } set when the constructor was automatically called. ]]> </mx:Script> <mx:TextArea x="10" y="10" id="displayText"/> </mx:Application>

The output of the trace statement is “John” as shown in Figure 3-6.

71


72

Flex 3: A Beginner’s Guide

Figure 3-6 The constructor set value displays

Your constructor may have the public attribute, or it can be omitted. But remember, it cannot be any other type than public. If your class is derived from another class, then it will automatically call the parent class’ constructor before executing the local constructor. It’s also possible to call methods from the parent class using the super prefix. If you reference a method in the parent class, prefix it with super. This helps other developers know where the method is invoked.

Instantiation Instantiation is the process of creating an object based on a class. Remember that the this keyword always refers to the current instance of a class after it has been created. Each time a class is instantiated, it gets its own local space to store any properties. The this keyword allows access to those properties. For example, public class MyTextClass { public var height:Number = 100; public var width:Number = 200; public var text:String = "myText"; } public var testTextClass:MyTextClass = new MyTextClass();

The new keyword instantiates an instance of the class you specify after it; in this case, the MyTextClass class. Any code in the constructor runs automatically. The constructor in this example sets the values for height, width, and text in this instance of the class through the use of the this keyword. Our new object is called testTextClass. Figure 3-7 illustrates the relationship of classes, methods, properties, and instances.


Chapter 3:

Getting Started

Figure 3-7 A high-level overview of classes, methods, and properties

Instance methods Instance methods are declared with the static keyword and work with instance properties. For example, a function to return the height of an object would be created as an instance method, since the height depends on the instance, not the class. Instance methods can access both static and instance variables. The static class variables can be referenced as if theyâ&#x20AC;&#x2122;re instance variables, unlike their access from outside the class, which requires referencing the class name and the variable. For example, the class CustomLogText extends the LogText class. The CustomLogText class includes a static variable that stores all text that has been set in CustomLogText. An instance variable tracks the length of the LogText string as new classes are instantiated. An instance method getLength() returns the length of LogText when the string was added for that instance as shown in Listing 3-5. Listing 3-5 getLength() instance method public class CustomLogText extends LogText { public static var LogText:String = ""; public var LogLength:int; public function CustomText () { LogText = LogText . text; LogLength=LogText.length; } public function getLength () : int { return (LogLength); } }

73


74

Flex 3: A Beginner’s Guide

If you don’t want any other class to override a method you define in your class, then you can define the method with the keyword final. To redefine an inherited method, use the override keyword.

Static Methods Just as it can have static properties, a class can also have static methods. A static method is associated with the class instead of the instance. Therefore it can only be called by referencing the class. These methods are useful for limiting the scope of a method to the class and not the instance properties. A method should be defined as static if it doesn’t need to access data from the instances. For example, a help function to convert lengths between feet and meters doesn’t need to access the instance properties. Static methods cannot use the this keyword, because that’s used to access instance properties. This is unlike some other OOP languages where static methods are not inherited.

Getter and Setter Methods It’s common practice for object-oriented classes to store information in protected properties and force the users of the class to access those values using the get and set functions that work on the instance properties. These functions enforce the encapsulation principles of object-oriented design. They also reduce the number of extra methods that must be defined, two for each property more than traditional get and set methods. For example create a class that implements getter and setter methods as in Listing 3-6. Listing 3-6 Class getter and setter mehtods class RestictAccess { private var restrictedProperty:Number; public function get publicGetSet():Number{ return restricedProperty; } public function set publicGetSet(setNumber:Number):void { restrictedProperty = setNumber; } }

The property restrictedProperty cannot be accessed directly; however, it can be accessed using a pseudo-property called publicGetSet that maps to the set and get functions defined in the RestrictAccess class. To illustrate how this works, this example creates an instance of the RestictAccess class and accesses the variable using publicGetSet:


Chapter 3:

Getting Started

<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete = "initApp()"> <mx:Script> <![CDATA[ public function initApp():void { var myAccess:RestrictAccess = new RestrictAccess(); myAccess.publicGetSet = 123; displayText.text = String(myAccess.publicGetSet); } ]]> </mx:Script> <mx:TextArea x="10" y="10" id="displayText"/> </mx:Application>

The example displays “123”.

Inheritance One of the most useful features of OOP is the ability to inherit properties and methods from classes. Instead of starting from scratch to enhance functionality, you can start with a base class and simply redefine or extend the parts of it that you’d like. Sometimes the class where the inheritance occurs is also called a super class. The class that inherits is usually called the subclass. Inheritance also means that you can modify how a class works without modifying the super class itself. To specify that a class inherits from another class, use the extends keyword. Each subclass inherits all non-private methods and properties of its super class. Therefore, any method from the super class can also be called from the subclass and any property of the super class can also be accessed from the subclass. This means that anywhere that a super class could have been used, a subclass can take its place. For example, if a method defines a parameter of type Text, an argument of type Error can also be passed because Error extends Text: function display(textToDisplay:Text) {} var myError:Error = new Error(); display(myError);

Class Specifications You can think of the class as a template for creating an object; it defines what methods the object supports and the properties it stores. The class itself doesn’t do anything; it just specifies the design, which includes the methods, properties, and inheritance of the class.

75


76

Flex 3: A Beginner’s Guide

You must create a new object based on a class to do any real work. If the class has a constructor, it is called during this process to initialize the object.

Understanding MXML Namespaces MXML inherits its concept and handling of namespaces from XML. XML namespaces are a way of naming your XML elements to avoid conflicting with the names another XML developer may choose. For example, you can define the XML element title to represent the title of a document, whereas someone else may define it as a person’s title such as Director of Engineering. The default namespace for MXML is called mx. The following line defines this mapping using the xmlns keyword within the <mx:Application> tag. It’s located at the beginning of your MXML file: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" horizontalAlign="center" verticalAlign="middle" >

This code snippet specifies that mx represents the mxml namespace. The Universal Resource Identifier (URI) listed after the equal sign doesn’t represent a real web site but is there to create a unique string to differentiate all namespaces from each other. For example, if you go to http://www.adobe.com/2006/mxml, you’ll get a page not found error.

The Flex Config File The URL is used within a special file called flex-config.xml in the SDK/frameworks directory that was included when you installed Flex Builder or the SDK. This file defines a mapping between the URI and the manifest file.

The Manifest File The manifest file, as shown in Listing 3-7, tells the Flex compiler how to find the ActionScript code that corresponds to the MXML tags in the namespace, as shown in Listing 3-8. Remember that when your MXML files are compiled, they’re turned into ActionScript code. Listing 3-7 Manifest of components <namespaces> <!-- Specify a URI to associate with a manifest of components for use as MXML --> <!-- elements. --> <namespace>


Chapter 3:

Getting Started

<uri>http://www.adobe.com/2006/mxml</uri> <manifest>mxml-manifest.xml</manifest> </namespace> </namespaces>

The mxml-manifest.xml file contains the following (note that the middle section of the code was deleted) component entries that map MXML tags from the mx namespace to their ActionScript source code classes: Listing 3-8 mx Namespaces <?xml version="1.0"?> <componentPackage> <component id="Accordion" class="mx.containers.Accordion"/> <component id="AddChildAction" class="mx.effects.AddChildAction"/> <component id="AnimateProperty" class="mx.effects.AnimateProperty"/> <component id="Application" class="mx.core.Application"/> <component id="ApplicationControlBar" class="mx.containers.ApplicationControlBar"/> <component id="ArrayCollection" class="mx.collections.ArrayCollection"/> <component id="Blur" class="mx.effects.Blur"/> <component id="Box" class="mx.containers.Box"/> <component id="Button" class="mx.controls.Button"/> <component id="ButtonBar" class="mx.controls.ButtonBar"/> . . . </componentPackage>

Referencing Namespaces in Your Code To use the standard Flex components, reference them using the mx prefix. For example, to reference the Text Area component: <mx:TextArea id="textLive"/>

When creating your own Flex components, it’s best practice to place them in a separate namespace. This assures that your components won’t conflict with any of the standard mx components. In Chapter 4, we’re going to talk about Flex Builder, how to build a user interface, and using controls.

77


This page intentionally left blank


Chapter

4

Working with Flex Builder

79


80

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

Flex Builder Modes

Building a User Interface

Controls

Modifying Controls

Text Controls

Select and Modify Text

Menu Control

Menu Attributes

Running Your Application

F

lex Builder is similar to Dreamweaver. Where Dreamweaver uses a code or design view or both, the Flex Builder uses the developer or debug modes. Perspectives get delivered with each plug-in you install so that you can utilize their capabilities. When you begin creating your Flex application, start with the main MXML file. Then you can embed ActionScript and CSS code into the MXML file, or you can create separate ActionScript or CSS files and import them into your MXML files. In order to debug your files, use the Code Editor to locate and highlight lines of code to fix any errors you find in your code. Debug includes numerous views, including: debug, breakpoints, console, variables, and expressions. Additionally, you can set breakpoints to stop your script execution in order to inspect the variable values or other information up to that point in your code. Then there are containers and controls, which are components that define how your application looks and feels. The relationship between containers and controls in Flex is similar to the relationship of an HTML table and form elements embedded in it. Flex Builder includes a constraint-based layout format to make arrangement of components


Chapter 4:

Working with Flex Builder

automatic when a user resizes the Flex application window. Navigator containers allow logical grouping of your containers into views. Either adding their MXML tags or dragging them from the Navigator branch of the Components panel in Flex Builder can add navigator controls to your Flex application. ActionScript can modify or provide data from a component, since Flex converts the MXML component to ActionScript when you run the build process. Controls are what exchanges information with the user of your software application. Data can be displayed, and user input could be given, depending on the type of control that you use. Controls are placed within containers that define their layout. There is a class hierarchy of controls. All controls have definite rules for determining their size. Several different types of controls are: text-based, data provider, menu, sizing, and positions. You can select and modify text using various controls. Then there are arrays. Arrays are a special kind of variable that stores many pieces of data. Arrays allow you to access any of the values stored in them individually yet still copy and manipulate the array as a whole. The RichTextEditor displays and edits text but includes extra controls for formatting the text such as font style, size, and adding URL links. Menus have different attributes, which affect how they display and react to user interaction. Menus appear in the upper left-hand corner of the application by default. You can override the menu’s default. A data provider for a menu control can be defined as one of several types. The first is an XML object; the second is a multilevel nested array. Most of what is discussed in this chapter is how to create, modify, and navigate controls.

Flex Builder Modes There are two Flex Builder modes: Developer and Debug. Flex Builder uses Eclipse’s concept of perspectives to display only the editors and views that are necessary for the current mode. The two perspective modes are developing and debugging, but you can only view one at a time. The active perspective automatically changes for certain tasks. Figure 4-1 shows Flex Builder just after startup in the Development perspective. Perspectives are delivered with each plug-in, and you can customize them to your liking. A group of editors and views that support a specific task or group of tasks are combined into a perspective, and they change automatically, depending on what they’re supporting. For example, when you create a Flex project, the workbench switches to the Flex Development perspective, and then when you begin to debug, the new perspective

81


82

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 4-1 Flex Builder in the Development perspective with Code Design view

displays when the first breakpoint is encountered. Figure 4-2 shows Flex Builder in the Debug perspective. Additionally, you can manually switch perspectives by selecting Window | Open Perspective from the main menu, or you can use the perspective bar, which is located on the workbench toolbar. If youâ&#x20AC;&#x2122;re using the plug-in configuration of Flex Builder and have other Eclipse plug-ins installed, you may have many additional perspectives. In order to create and subsequently customize a perspective, you can select, place, and size the editors and views that you need to accomplish your development tasks.

Development The Flex Builder Code Editor is used to write your Flex and ActionScript applications. When you begin creating your Flex application, start with the main MXML file. Then you can embed ActionScript and CSS code into the MXML file, or you can create separate ActionScript or CSS files and import them into your MXML files. The Code Editor is part of the Flex Developer perspective, which also includes all supporting Navigator,


Chapter 4:

Working with Flex Builder

Figure 4-2 Flex Builder in the Debug perspective

Problems, and Outline views. Once you’ve created a project, you’re switched to the development perspective in order to begin developing your application. The Navigator view as shown in Figure 4-3 displays the project files in a tree view. The Flex Development perspective contains the following elements: ●

Code Editor This view enables you to write MXML, ActionScript, and CSS code. The Code Editor gives you code hinting and formatting and a design mode where you can visually define your Flex application layout; additionally, you can complete integration with the Flex Builder debugging tools, and there are syntax error checking and problem reporting.

Navigator view This view displays all of the projects in your workspace and all of the resources, including folders and files, within your projects.

Problems view This view displays your syntax and other compilation errors that are detected by the compiler. By default the compiler builds your Flex project each and every time you make a change to it, so you get almost immediate feedback as you create your code.

83


84

Flex 3: A Beginner’s Guide

Navigator view Editor

Outline view

Problems view

Figure 4-3 The Flex Builder in Design view

Debugging When you need to debug your application, the Flex Debugging perspective contains the tools you need to do so. In the context of debugging, the Code Editor is used to locate and highlight lines of code in order for you to fix the errors. For example, you can set breakpoints to stop script execution in order to inspect the variable values or other information up to that point in your code. A breakpoint basically establishes a place for your Flex application to pause. By pausing the application, you can then view a snapshot of the application’s current state. Another way to utilize breakpoints is to use them or functions to see when your value changes. The Flex Debugging perspective automatically displays when you begin a debug session. You can also switch to it using the perspective bar, located at the right edge of the main toolbar. There are a few ways to manage breakpoints: ●

You can set or remove a breakpoint by selecting the desired line in the left-hand numbered column (shown in Figure 4-4) and using CONTROL-CLICK for the Mac or right-click to Toggle Breakpoint in Windows XP.


Chapter 4:

Working with Flex Builder

All breakpoints are listed here.

Code execution pauses at this line.

Figure 4-4 Breakpoint Numbers column

You can also set or remove a breakpoint by going to the desired line and right-clicking. A menu displays with the Set Breakpoint option in Flex 2.0; however, in Flex 3.0 and above there is no Set Breakpoint—the selection is Toggle Breakpoint. If you already set a breakpoint for the selected line, you can remove the breakpoint option.

Most of the time you’ll end up establishing numerous breakpoints. You can remove all the breakpoints from a selected document simultaneously by selecting File | Edit | Remove All Breakpoints in Flex 2.0; however, in Flex 3.0 and above the Run menu lists these options: Toggle Breakpoint, Toggle Line Breakpoint, Toggle Method Breakpoint, or Skip All Breakpoints.

You can also remove all the breakpoints by right-clicking the Code view and selecting Toggle Breakpoint; however, you can Remove All Breakpoints by navigating to Run | Remove All Breakpoints.

85


86

Flex 3: A Beginner’s Guide

The Flex Debugging perspective contains the following views: ●

Debug view The Debug view (sometimes referred to as the callstack) displays the stack frame of the Flex application suspended thread. Use the Debug view to manage the debugging process. For example, the Debug view allows you to resume or suspend the thread or step into and over code statements.

Breakpoints view The Breakpoints view lists all the breakpoints you set in your project. You can double-click a breakpoint and display its location in the Code Editor. You can also disable, skip, and remove breakpoints.

Console view The Console view displays trace statement output that was in your ActionScript code.

Variables view If you’re familiar with other debuggers, the Variables view serves the same purpose as the Locals window does in other debuggers. It displays information about the variables in the currently selected stack frame.

Expressions view Once again, if you’re familiar with other debuggers, the Expressions view serves the same purpose as the Watch window does in other debuggers. It’s used to monitor a set of critical variables. You can select the critical variables in the Variables view and add and monitor them in the Expressions view. You may modify, add, and remove variables within the Expressions view.

Building a User Interface Flex applications are built using components. Components define how the interface looks. There are two types of components: ●

Containers

Controls

Containers Containers control how Controls are placed on the screen. Controls allow your application to display information and interact with the user. Examples of controls include Text Input fields, Buttons, and Form Elements. Containers are rectangular and can contain controls as well as other containers. They allow for a logical grouping of controls when the application runs. Together controls and containers define the user interface of your application. Examples of containers include Box, Grid, and Forms.


Chapter 4:

Working with Flex Builder

The relationship between containers and controls in Flex is similar to the relationship of a table and form elements embedded in an HTML table. The table works like a Flex container, while the form elements act like controls in Flex. Flex Builder can be used to add containers, controls, and MXML code to your application. MXML containers and control names map to the ActionScript classes that implement them. MXML attributes can initialize attributes of the underlying class, for example, CSS styles and class attributes such as the visibility of the underlying ActionScript class.

The Application Container The application container is the parent container of other containers. It represents the entire display area of the Flex application in the Flash Player. As the base layer it holds all other defined containers. Any container thatâ&#x20AC;&#x2122;s placed inside another container becomes a child container. Therefore, all containers are children of the application container. Child containers inherit the properties of their parent containers, including settings such as size and position. However, these properties can be overridden at the child level. The idea is to automate the assignment of properties yet allow customization. When developing an application, pick a layout for your containers and use that layout on all screens, since it provides a consistent user experience. This not only makes your application easier to use but also makes development simpler, since each page follows the same model.

Constraint-Based Layout Flex Builder includes a constraint-based layout format to make arranging of components automatic when a user resizes the Flex application window. Constraint-based layouts use containers with the layout property set to absolute. To set the layout property to absolute, specify the following in the MXML tag: layout = absolute

Absolute positioning allows for setting constraints on how much your contained component stretches or moves when the container is resized. For example, to place text that remains 20 pixels from the top of the container and horizontally centered: 1. Drag a text element to the Design view. 2. Select Center from the pop-up menu that appears when you click the blue dot on either

the left or right side of the Text component.

87


88

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

3. Select Anchor from the blue dot on the top of the Text component. 4. On the Layout pane, change the value for Top to 20 to specify an offset from the top of

the parent container. 5. The Flex Builder Design and Layout panes should now look like Figure 4-5.

NOTE Constraints can only be set relative to the edge of their parent container and no other container. Constraint control set relative to Top

Constraint control set to Center

Constraint control in default state

Center the component relative to the container. 20 pixels relative to the top of the container

Figure 4-5 The Text component centered horizontally and ten pixels from the top


Chapter 4:

Working with Flex Builder

The layout pane in Flex Builder has settings for x, y, width, and height. You can also set the constraint by checking any of four blue dots that appear on the sides of components. Once the dot is selected, a pop-up menu displays with choices for Anchor, Unanchored, and Center. Selecting Center from the drop-down menu affects top and bottom or left and right simultaneously, since the offset is from the center instead of the side nearest the constraint dot.

NOTE Each placement also allows specifying an offset.

Table 4-1 lists the combinations of check boxes to select for common component placements. Flex supports many different controls that can be placed within containers, including Grids, HBoxes, and Tile containers.

Navigator Containers Navigator containers allow logical grouping of your containers into views. An example of a Navigator container is the TabNavigator container that allows switching the view based on tabs that appear at the top of the container. Tabbed containers are often used in option windows to display only the containers that are related to a category of the options such as file paths or formatting options.

Desired Alignment

Constraint Dot to Select

Center horizontally

Select center from left or right dots

Center vertically

Select center from top or bottom dots

Maintain position and size

None

Move horizontally

Absolute from left dot

Move vertically

Absolute from top dot

Move both horizontally and vertically

Absolute from left and top dots

Resize horizontally

Absolute from left and right dots

Resize vertically

Absolute from top and bottom dots

Resize both horizontally and vertically

Absolute for all dots

Table 4-1 Absolute Positioning Reference

89


90

Flex 3: A Beginner’s Guide

You can add navigator controls to your Flex application either by adding their MXML tags or by dragging them from the Navigator branch of the Components panel in Flex Builder. Flex Builder must be in Design code display mode to add navigators. Navigators available are listed in Table 4-2. The views within a Navigator container are considered child containers. The Accordion, TabNavigator, and ViewStack are the only Navigator containers that can contain child containers. A linked ButtonBar, LinkBar, or TabBar controls the ViewStack container’s active view.

Controls Controls are what exchange information with the user of your software application. Data can be displayed, and user input could be given, depending on the type of control that you use. Controls are placed within containers that define their layout. Examples of controls include TextAreas, Buttons, and CheckBoxes. Containers are usually placed on your page hierarchically while defining logical groupings of elements and allowing information to be inherited from parent container(s). Since the application container is the base or root container for all applications, you place containers or components within the Application container.

Navigator

Purpose

Accordion

Accordion creates and manages a stack of Navigator buttons to select a view that appears below the selected button.

TabNavigator

A TabNavigator contains multiple views. Tabs along the top of the container control the displayed view.

ViewStack

A ViewStack contains one or more views. Only one view can display at once. Since it doesn’t have a built-in means of switching views, a ButtonBar, LinkBar, TabBar, or ToggleButtonBar must be used with it to select the active view.

ButtonBar

ButtonBar defines a horizontal or vertical group of related push buttons to control the active view of a ViewStack.

LinkBar

A LinkBar displays a bar of links to control the active view of a ViewStack.

TabBar

A TabBar displays a bar of links to control the active view of a ViewStack.

ToggleButtonBar

A ToggleButtonBar works with a ViewStack to control which view is active by selecting a button from a bar. Buttons remain selected until they’re clicked again or another button is selected. Only one button can be selected at a time.

Table 4-2 Summary of Navigator Containers


Chapter 4:

Working with Flex Builder

TIP The MXML tag for the Application container is the <mx:Application> tag.

This example uses MXML to create a form and places a CheckBox within the Form. When the MXML codes runs in the browser, it looks like Figure 4-6. The CheckBox label is set to “Logging” by specifying an MXML parameter called label. Similarly, the text that appears after the check box is set to “Active.” The following code can be entered into the Source view to create the example: Listing 4-1 Code for Logging Example <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Form x="162" y="95"> <mx:FormItem label="Logging"> <mx:CheckBox label="Active"/> </mx:FormItem> </mx:Form> </mx:Application>

The example can also be created by dragging Form, FormItem, and CheckBox components onto the Design Layout window on top of each other. The Label properties also need to be set if using the Design view for the FormItem and the CheckBox. The example creates a hierarchy of containers as shown in Figure 4-7.

Figure 4-6 The CheckBox with its Label properties set

91


92

Flex 3: A Beginner’s Guide

Figure 4-7 The CheckBox container within the Application and Form containers

Arrays Arrays are a special kind of variable that stores many pieces of data. Arrays allow you to access any of the values stored in them individually yet still copy and manipulate the array as a whole. When working with arrays, there are two new terms to become familiar with: elements and indexes. Elements are the values that are stored in the array. Each element in the array is referenced by an index that differentiates the element from any other unique element in the array. The index value can be a number or a string, but it must be unique. You can think of an array as like a spreadsheet or a database that has only two columns. The first column uniquely identifies the row in the spreadsheet, while the second column contains a stored value. ActionScript can modify or provide data from a component, since Flex converts the MXML component to ActionScript when you run the build process. This example uses ActionScript to populate the selections of a ComboBox component. The initialization function produces an array that’s loaded by the component’s creationComplete parameter. Listing 4-2 Array using the creationComplete parameter <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ private function myBox_initialize():void { myBox.dataProvider = [ Create the array of box options.


Chapter 4:

Working with Flex Builder

'none', 'some', 'all']; } ]]> </mx:Script> <mx:ComboBox x="216" y="126" id="myBox" creationComplete="myBox_initialize();"/> </mx:Application>

Set the initializer.

The sample code creates a screen as seen in Figure 4-8, when the user clicks the choices.

Text-Based Controls Text-based controls allow for the displaying and editing of text. Some text controls can be set to enable text editing. The control may also allow for a single or multiple lines of text as shown in Table 4-3. The RichTextEditor is a combination of a TextArea and several controls that define the text appearance. When adding it to your application, it appears as a single control.

Figure 4-8 The ComboBox initialized to the data from the array

93


94

Flex 3: A Beginner’s Guide

Control

Option to Be Editable

Multiline

Text

No

No

Label

No

No

TextArea

Yes

Yes

TextInput

Yes

No

RichTextEditor

Yes, also supports formatting such as font characteristics

Yes

Table 4-3 The Capabilities of the Text Controls

Data Provider Controls Data provider controls are controls that are built from a data provider data-source object such as an array. The last example with the ComboBox used an array returned from a function as its data source. Only a handful of Flex components are data provider controls; these include the ComboBox, DataGrid, and Tree controls. Additionally, DataGrid elements can be populated from a data provider data source. These controls separate the data source from how it’s presented and modified in the data provider control. The separation of the data and the control insulates the effects of changing either. A single data source can provide data to multiple data provider controls. Examples of possible data sources in Flex include the Ajax-like HTTPService and the LiveCycle Data Services package that includes Data Management and Messaging Services.

Menu Controls There’s one more type of control to discuss. For working with menus, there are menu controls. Menus are great for displaying hierarchical selection data. Flex has three menu controls: Menu, MenuBar, and PopUpMenuButton. All of them can have labels and optional icons for each entry in the menu. They can also launch tasks when a user selects a menu item. The Menu control is a simple menu that can have submenus and is launched by a user event. This is the only menu type that must be created and controlled by ActionScript. MenuBar maps out the first level of the menu horizontally and displays submenus; essentially, it’s a horizontal menu bar. The PopUpMenuButton control displays a menu after clicking a button. It’s based on the PopUpButton control. Then the button label changes to reflect the last menu selection. Table 4-4 lists all Flex controls.


Chapter 4:

Working with Flex Builder

Control

Description

Alert

This displays a pop-up message informing the user of a problem.

Button

This is a clickable button that can contain text and an image.

ButtonBar

This displays buttons in a bar, all for similar tasks.

CheckBox

This allows the user to see and modify a Boolean value.

ComboBox

This is a drop-down box a user can select values from to populate an attached text field.

ColorPicker

This displays a selectable drop-down color swatch palette, similar to PhotoShop.

DataGrid

This displays data in a tabular format.

DateChooser

This displays an entire month of days, from which you can select one.

DateField

This displays the date with a calendar icon. If a user clicks inside the control, a DateChooser pop-up displays with the month and days.

HorizontalList

This displays a horizontal list of items.

HRule/VRule

This displays a single horizontal rule (HRule) or vertical rule (VRule).

HSlider/VSlider

This allows users to select a value by moving a slider along the slider track.

Image

This imports image files, such as GIF, JPEG, PNG, SVG, and SWF files.

Label

This displays a non-editable single-line field label.

LinkBar

This displays a horizontal row of LinkButton controls designating link destinations.

LinkButton

This displays a hypertext link.

List

This displays a scrollable array of choices.

Menu

This displays a pop-up menu of individually selectable choices, similar to the File or Edit menu of most software applications.

MenuBar

This displays a horizontal menu bar that contains one or more submenus of controls.

NumericStepper

This displays a dual button to increase or decrease the underlying variable value.

ProgressBar

This provides visual feedback of how much time remains for the current operation.

RadioButton

This displays a set of buttons, one of which is selected at any time.

RadioButton Group

This displays a group of RadioButton controls with a single-click event listener.

RichTextEditor

This includes a multiline editable text field and controls for specifying text formatting.

ScrollBar (HScrollBar This displays horizontal and vertical scroll bars, HscrollBar for horizontal and and VScrollBar) VScrollBar for vertical.

Table 4-4 Flexâ&#x20AC;&#x2122;s Controls and Their Purpose

95


96

Flex 3: A Beginner’s Guide

Control

Description

SWFLoader

This displays the contents of a specific SWF file or JPEG file.

TabBar

This displays a horizontal row of tabs.

Text

This displays a non-editable multiline text field.

TextArea

This displays an editable text field for users that accept more than a single line of input.

TextInput

This displays an editable text field for a single line of user input. It can contain alphanumeric data, but input is interpreted as a String data type.

TileList

This displays either a tiled vertical column or a horizontal row list of items.

ToggleButtonBar

This displays a row of related buttons that all have a common appearance.

Tree

This displays hierarchical data arranged as an expandable tree.

VideoDisplay

This incorporates streaming media into Flex applications.

Table 4-4 Flex’s Controls and Their Purpose (continued)

Modifying Controls As we discussed already, Flex controls share a common class hierarchy; therefore, you use a similar procedure to configure all controls. Some of the most important aspects of controls are as follows: ●

Class hierarchy of controls

Sizing controls

Positioning controls

Changing the appearance of controls

Containers, like other components in Flex, inherit properties from their super classes. For example, the Form container inherits from the Container class, which in turn inherits from other classes. The complete inheritance for Form is as follows: Form <- Container <- UIComponent <- FlexSprite <- Sprite <DisplayObjectContainer <- InteractiveObject <- DisplayObject <EventDispatcher <- Object

Figure 4-9 shows the inheritance graphically.


Chapter 4:

Working with Flex Builder

Figure 4-9 Inheritance from object up to form

Form inherits all of the methods and properties of the objects in the chain. Therefore, you can access the contentMouseX property, a property of the Container class, to get the position of the mouse relevant to the container for a form container. Many of these properties can be set from your MXML codes as tags or directly using ActionScript. Many of the properties that control the size, position, and appearance of your containers are actually inherited from parent classes of the containers.

Class Hierarchy of Controls The Sprite and UIComponent classes are the base classes for all Flex components. Subclasses of the UIComponent class can have shape, draw themselves, and be invisible. Each subclass can participate in tabbing, except for low-level events like keyboard and mouse input. They can also be disabled so that they donâ&#x20AC;&#x2122;t receive mouse and keyboard input. Sprite is like a movie clip without a timeline. So it can contain graphics and other containers but nothing with a timeline.

Sizing Controls All controls have definite rules for determining their size. For example, a Button control sizes itself to fit its label text and optional icon image, while an Image control sizes itself to the size of the imported image. Each control has a default height and a default width. Each standard control has a default size specified in the description of the specific control.

97


98

Flex 3: A Beginner’s Guide

Given this information, keep in mind that the default size of a control is not always a fixed value. For example, when you use a Button control, the default size is large enough to fit its label text and optional icon image. But then at runtime, Flex calculates the default size of each control and, by default, doesn’t resize the control from its original default size. A good idea would be to set the height or width attributes in MXML to percentages, such as 50 percent, or use the percentHeight or percentWidth ActionScript properties as percentage values, such as 50. This enables Flex to resize the control in the corresponding direction. If you’ve specified a percentage for the parent container of the control, then Flex attempts to follow that established guideline. Now, in the event that there isn’t enough space available, percentages are scaled, all the while retaining their relative values. For example, you can set the width of a Comments box to scale with its parent container as the parent container changes size, as shown in this example: <mx:TextInput id="comments" width="100%" height ="20"/>

You can also specify explicit sizes for a control. In MXML or ActionScript you set the height and width properties to numeric pixel values. The following example sets the height and width of the addr2 TextInput control to 100 pixels and 20 pixels, respectively: <mx:TextInput id="addr2" width="100" height ="20"/>

NOTE Placement values such as width and height default to pixels as the measurement unit.

If you want to resize a control at runtime, use ActionScript to set its width and height properties. For example, you use the click event listener for the following Button control, which sets the width property of the addr2 TextInput control to increase its width by 10 pixels. <mx:Button id="button1" label="Slide" height="20" click="addr2.width+=10;"/>

NOTE The preceding technique works even if the width property was originally set as a percentage value. The stored values of the width and height properties are always in pixels.

Many components have arbitrarily large maximum sizes, which means that Flex can make them as large as necessary to fit the requirements of your application. You can use the maxHeight, maxWidth, minHeight, and minWidth properties to set explicit size ranges for each component.


Chapter 4:

Working with Flex Builder

Positioning Controls As we discussed earlier, most containers have predefined layout rules that automatically determine the position of their children. The Canvas container absolutely positions its children, while the Application and Panel containers optionally let you use absolute or container-relative positioning. To absolutely position a control, set its x and y properties to specific horizontal and vertical pixel coordinates within the container. Itâ&#x20AC;&#x2122;s important to remember that these coordinates are relative to the upper-left corner of the container, which is coordinates (0,0). Your x and y values can be either positive or negative integers. You can use negative values to place a control outside of the visible area of the container, and then use ActionScript to move the child to the visible area, for example as a response to an event. The following example places the TextInput control 150 pixels to the right and 150 pixels down from the upper-left corner of a Canvas container: <mx:TextInput id="addr2" width="100" height ="20" x="150" y="150"/>

At runtime to reposition a control within an absolutely positioned container, set its x and y properties. For example, the click event listener for the following Button control moves the TextInput control down ten pixels from its current position, as shown here: <mx:Button id="button1" label="Slide" height="20" x="0" y="250" click="addr2.y = addr2.y+10;"/>

Besides sizing and positioning, you can also change the appearance of controls. Flex offers you an enormous amount of flexibility when it comes to designing your application.

Changing the Appearance of Controls Styles, skins, and fonts enable customization of the controlâ&#x20AC;&#x2122;s appearance. Each control defines a set of styles, skins, and fonts that you can set; some are specific to a particular type of control, and others are more general. There are several different ways for you to configure the appearance of your controls. For example, you can set styles for a specific control in its MXML tag, by using ActionScript, or globally for all instances of a specific control in an application by using the <mx:Style> tag. Then there are themes. They define the look and feel of a Flex application. A theme can define something as simple as the color scheme or common font for an application, or it can be a complete re-skinning of all the Flex components. In some styles, however, you just wonâ&#x20AC;&#x2122;t be able to alter the controls for those properties.

99


100

Flex 3: A Beginner’s Guide

Text Controls Flex text-based controls let you set and get text by using the following properties: ●

Text

HtmlText This is rich text that represents formatting by using a subset of HTML tags. You can also include bulleted lists and URL links.

This is plain text without any formatting information.

Both properties set the same underlying text, but you can use different formats. For example, you can do the following to your text with a variety of properties. ●

You can set formatted text by using the htmlText property.

You can change your formatted text to a plain text string by using the text property.

You can set formatted text in user-editable text controls (TextInput, TextArea, RichTextEditor) by setting the text string with the text property and formatting a section of this text by using the TextRange class.

If you get the text back by using the htmlText property, the property string includes HTML format tags.

Text Property You can use the plain text property to specify a text string that displays in a text control or in order to get the text in the control as a plain text string. When you set this property, any HTML tags in the text string appear in the control as literal text. You can’t specify text formatting when you set the text property, but you can format the text in the control. You would use the text control styles to format whatever text is in the control, and then you’d use the TextRange class to format specific ranges of text. The following code line uses a text property to specify label text: <mx:Label text="This is a simple text label"/>

The way you specify special characters, including quotation marks, greater than and less than signs, and apostrophes, depends on whether you’re using them in MXML tags or in ActionScript. Another contingency is whether you specify the text directly or wrap the text in a CDATA section.

NOTE If you specify the value of the text property by using a string directly in MXML, Flex collapses white space characters. If you specify the value of the text property in ActionScript, Flex does not collapse white space characters.


Chapter 4:

Working with Flex Builder

The htmlText Property You use the htmlText property to set or get an HTML-formatted text string. You can also use one tag that is not part of standard HTML, the textFormat tag. You can specify text-formatting styles by using the Flex styles. Basically, you set a base style, such as the font characteristics or the text weight using a style, and override the base style in sections of your text by using tags, such as the <font> tag. This is similar to using CSS when you’re designing something for the web. In the following example, the <mx:Text> tag styles specify the following for the characteristics blue, italic, 14-point text, and the <mx:htmlText> tag includes HTML tags that override the color and point size. Listing 4-3 Overriding HTML Tags <?xml version="1.0"?> <!-- textcontrols/HTMLTags.mxml --> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="450" backgroundGradientColors="[#FFFFFF, #FFFFFF]">

Create the Text

<mx:Text width="100%" color="blue" fontStyle="italic" fontSize="14"> component. <mx:htmlText> Specify the HTML text. <![CDATA[This is 14-point blue italic text.<br><b><font color="#000000" size="10"> This text is 10-point black, italic, and bold.</font></b>]]> </mx:htmlText> </mx:Text> </mx:Application>

Listing 4-3 results in the following output: ●

This is 14-point blue italic text.

This text is 10-point black, italic, and bold.

Select and Modify Text You can select and modify text using the following controls: ●

TextArea

TextInput

RichTextEditor

The TextArea, TextInput, and the RichTextEditor controls all provide the following text selection properties: ●

The setSelection() method selects a range of text. You’re defining the starting and ending point of your text.

101


102

Flex 3: A Beginner’s Guide

SelectionBeginIndex and selectionEndIndex set or return the zero-based location in the text of the starting point and the position immediately after the end of a selection.

TextArea The TextArea control displays and allows editing of multiple lines of text. It may contain plain text or HTML markup. The text it displays can be set by the text or htmlText properties discussed previously. If the text is larger than the control, a vertical scroll bar automatically displays. The behavior of the TextArea can be modified by its properties. The TextArea can be set to not allow editing by setting the editable property to false. It can also hide text, which is useful for entering passwords, by setting the displayAsPassword property.

Define the TextArea Control To define a TextArea control, either drag the component onto the Design view of Flex Builder or manually add a <mx:TextArea> tag. As with any other component, you can specify an id attribute to allow your ActionScript to modify the control. <?xml version="1.0"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:TextArea id="Comments" width="200" height="100" text="Comments welcome."/> </mx:Application>

Figure 4-10 displays the Design mode for the preceding code.

TextInput The TextInput control is similar to TextArea, except it works with only a single line of text. It works with the text and htmlText properties to set the displayed text. It supports disabling editing by setting the editable property to FALSE. Password text can be hidden. The TextInput control resize differently than a TextArea. Because it displays only one line of text, a scroll bar does not display if more text is entered than can be displayed. If a width is not specified when creating the TextInput, its size is based on text set by the text or htmlText properties. It doesn’t change size as a user enters text. To define a TextInput control, either drag the component onto the design view of Flex Builder or manually add a <mx:TextInput> tag. As with any other component, you can


Chapter 4:

Working with Flex Builder

Select the component to view its properties.

Sets and displays the Componentâ&#x20AC;&#x2122;s width Sets and displays the Componentâ&#x20AC;&#x2122;s height Sets and displays the Text/Label property Sets and displays the ID property

Figure 4-10 The Flex Properties panel reflects the values for ID, text, width, and height.

specify an id attribute to allow your ActionScript to modify the control. This code creates a TextInput control called user_name: <?xml version="1.0"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:TextInput width="80" id="user_name" /> </mx:Application>

103


104

Flex 3: A Beginner’s Guide

RichTextEditor The RichTextEditor displays and edits text like the TextArea but includes extra controls for formatting the text such as font style, size, and adding URL links. It works with the text and htmlText properties to set text that displays initially. The editing controls appear at the bottom of the editor window. The RichTextEditor is constructed from a TextArea and a toolbar container. The toolbar also controls the color of the text, creating bulleted lists, alignment, and styles such as bold, italics, and underline. Users can modify the text as they wish using the formatting buttons. The rich text can be copied between Flex text components, but pasting to an external application like a word processor copies only the plain text equivalent. The RichTextEditor control does not change its size according to the size of the text. If the text does not fit in the editor’s display, scroll bars are automatically added. It’s possible to specify either the width or the height of the control. To define a RichTextEditor control, either drag the component onto the design view of Flex Builder or manually add a <mx:RichTextEditor> tag. As with any other component, you can specify an id attribute to allow your ActionScript to modify the control. This code creates a RichTextEditor control called comments: <?xml version="1.0"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:RichTextEditor id="comments" text="Write your comments here." /> </mx:Application>

Label Control The Label control is a single-line text field that you can’t edit. In order to create a Label control using MXML, apply the <mx:Label> tag. Specify a name for the label using the id parameter in your MXML to modify the label from ActionScript. The text it displays can be set by the text or htmlText properties. By default the Label control sizes itself large enough to contain the label’s text. If you specify a size for your label, make sure it’s large enough to hold the text or it will be truncated. This example creates a label that displays “Example Text”: <?xml version="1.0"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Label text="Example Text"/> </mx:Application>

The Label control has the following properties: ●

There is no backgroundColor property; therefore, the background is transparent.


Chapter 4:

Working with Flex Builder

Use styles or HTML to specify text formatting.

Your user cannot change the text, but the application can modify it.

The Label control is unable to take focus.

Control the alignment and sizing.

The text appears by itself without any borders. While it’s great to work with text, sometimes a menu is just what your application needs.

Menu Control The Menu control is a pop-up menu of ActionScript-created choices. These controls launch based on a user action, for example, clicking inside a radio button. Menu controls can be created using either an MXML XML object or an ActionScript array. There are four Flex menu item types: ●

Normal

Check

Radio

Separator Normal is the default. Table 4-5 describes each type. Each of these menu items supports several attributes to configure it.

Type Field Value

Description

Check

Selecting a check menu item toggles its toggled property. If the toggle is currently true, a check box is displayed by the menu item’s label.

Normal

Selecting a normal menu item opens a submenu if it exists or launches a change event.

Radio

Selecting a radio menu item activates the current item. Radio items operate in a group, and only one radio menu item can be selected at once. The currently selected item displays a solid circle next to its label and has its toggled property set to TRUE.

Separator

The separator item cannot be selected. It provides a horizontal line to separate groups of menu items.

Table 4-5 Menu Item Types

105


106

Flex 3: A Beginner’s Guide

Menu Attributes Each menu item can have several attributes set that affect how it displays and reacts to user interaction. These attributes are included in the data provider along with the item they affect. Table 4-6 lists them and their purpose. Menu controls determine their hierarchy (menus versus submenus) from the layout of the data provider information. The data provider entries also specify the label, icon, item type, and item attributes. The menu’s data provider is specified using the dataProvider property. If the information in the data provider changes, the menu layout also dynamically changes.

Data Provider Types A data provider for a menu control can be defined as one of several types. The first is an XML object; the second is a multilevel nested array. The XML must be in a valid format that complies with the E4X standard. To ensure properly formatted XML, use MXML tags like <mx:XML> and <mx:MXMLList> or a XML or XMLList object.

TIP Menus that change dynamically must use a collection such as ArrayCollection or XMLListCollection.

Attribute

Type

Description

enabled

Boolean

This specifies if the user can select the menu item (true), or not (false). If there’s no specification, the value is true.

groupName

String

This identifier associates radio button items in one group. GroupName is required but for radio types only.

icon

Class

This specifies an image asset class identifier. You can’t use this for check, radio, or separator types.

label

String

This specifies whatever text appears in the control. This is used for all menu item types except separator.

toggled

Boolean

This specifies if a check or radio item is selected. If there’s no specification, the value is false.

type

String

This specifies a specific type of menu item. The important values are check, radio, and separator. All other values are considered normal.

Table 4-6 Menu Control Attributes


Chapter 4:

Working with Flex Builder

When constructing XML to define a menu, select tag names that reflect their meaning as menu items and submenu items. For example, use <topItem> for the first-level items and <subItem> for submenu items.

NOTE Flex determines the menu level from the nesting of your XML tags, not their names.

Because an XML object created by the <mx:XML> tag automatically has a single entry at the root level, youâ&#x20AC;&#x2122;ll need to hide it. To do this, set the showRoot property to FALSE for the Menu, MenuBar, or PopUpMenuButton.

Menu Control Creation Menus appear in the upper left-hand corner of the application by default. You can override the default by specifying x and y coordinates when calling the show() command. Menus display until the user makes a selection or clicks outside the menu. To create a Menu control instance: 1. Call the createMenu() method with the data provider as the second parameter, such as var testMenu:Menu = Menu.createMenu(null, testMenuDataProvider, TRUE);

The first parameter is set to null since it optionally specifies the menuâ&#x20AC;&#x2122;s parent container. The second parameter is the name of the Data Provider object, in this case testMenuDataProvider. If you passed an XML data provider, specify the third parameter as FALSE to ignore the automatically created root. 2. Call the show() method to display the menu Instance: testMenu.show(20,20);

Listing 4-4 creates a Menu control. Listing 4-4 Create a Menu Instance <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.controls.Menu; // Method to create an Array-based menu. private function buildDisplay():void { var testMenu:Menu = Menu.createMenu(null, menuDataProvider, true); testMenu.show(20, 20); } Create and display the menu.

107


108

Flex 3: A Beginner’s Guide The children keyword tells the menu that this is an array of submenu items. // The Data Provider Array [Bindable] public var menuDataProvider:Array = [{label: "File", children: [ {label: "Save", enabled: false}, This item will be {label: "Open", type: "normal"} ghosted out. ]}, {label: "Type", children: [ {label: "Text", type: "radio", groupName: "group1"}, {label: "Image", type: "radio", groupName: "group1", toggled: true}, {label: "XML", type: "radio", groupName: "group1"} ]}, {label: "Auto Save", type: "check", toggled: true}, {label: "Highlight Keywords", type: "check", toggled: false} ]; ]]> </mx:Script> <!-- Button control to create and open the menu. --> <mx:Button x="250" y="10" label="Menu" click="buildDisplay();"/> </mx:Application>

Use the click event to launch the menu builder function.

The <mx:XML> tag defines the data control data. The menu is launched based on the Button control’s click event. An array is used as the data provider. The import command tells the Flex compiler that the code for the Menu components should be included. The path to the menu code is mx.controls.Menu. Figure 4-11 shows how this menu displays when the user’s mouse selects the Type menu.

Figure 4-11 The menu displaying the Type submenu


Chapter 4:

Working with Flex Builder

MenuBar Control The MenuBar control opens a submenu when your user selects a higher-level menu item. Then this submenu stays open until the user selects another top-level menu item, selects a submenu item, or clicks outside the MenuBar area. Use the <mx:MenuBar> tag to define a MenuBar control using MXML. You’ll need to apply an id value if you want to refer to a component that is elsewhere in your MXML application, which could be in another tag or even an ActionScript block. The MenuBar and Menu controls use the same data providers. Use the dataProvider property to specify information for the MenuBar control. These are some other little niggly things to keep in mind: ●

If you’re using a label attribute with your data provider, you need to use the at (@) sign for the label. For example: labelField="@label".

When you use the <mx:XML> tag, use a single root node and set the showRoot property to false.

You can list XML nodes using the <mx:XMLList> tag; the top-level nodes define the bar buttons.

MenuBar uses the dataProvider property as its default. This allows you to define the XML or XMLList object as a direct child of the <mx:MenuBar> tag.

Try This

Create a MenuBar Control

1. Open an MXML application in Flex Builder. 2. Call the file menuBar.mxml. 3. Add the code that follows, which has the direct child object using the

<mx:MenuBar> tag: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:MenuBar id="testMenuBar" labelField="@label"> <mx:XMLList> <menuitem label="File" > <menuitem label="Save" enabled="False"/> <menuitem label="Open"/> </menuitem> <menuitem label="Auto Save" type="check" selected="true"/> <menuitem label="Highlight Keywords" type="check" selected="false"/>

(continued)

109


110

Flex 3: A Beginner’s Guide

<menuitem label="Type" > <menuitem label="Text" type="radio" groupName="group1"/> <menuitem label="Image" type="radio" groupName="group1" selected="true"/> <menuitem label="XML" type="radio" groupName="group1"/> </menuitem> </mx:XMLList> </mx:MenuBar> </mx:Application>

4. Select Run menuBar from the Flex Builder Run menu. 5. Save the file if prompted to. 6. The MenuBar appears in your default browser.

The top rows of the MenuBar control displays the top level of the menu as buttons. In this example those buttons are “File,” “Auto Save,” “Highlight Keywords,” and “Type.” Figure 4-12 shows the MenuBar with the Type menu displayed by the user. Lastly, when using node tags you can assign any name to one. As you probably noticed, in the example, each node is named with the generic <menuitem> tag, but you can use <node>, <subNode>, or even <person>, and a lot of other ones.

PopUpMenuButton Control The PopUpMenuButton supports only a single-level menu. If your user selects an item from the pop-up menu, the primary button of the PopUpButton displays the icon and label of the selected menu item. This is a great control to use when you’ll have numerous user

Figure 4-12 The MenuBar control displays the top level as buttons


Chapter 4:

Working with Flex Builder

interactions. There is also the PopUpButton control where you create pop-up menu buttons that differ from the PopUpMenuButton. For example, you could create a button that doesn’t change the default action of the primary button after user interaction. Here’s how to create a PopUpMenuButton control: 1. Use the <mx:PopUpMenuButton> tag to define a PopUpMenuButton control. 2. Specify an id value if you’re going to refer to a component elsewhere in your

application such as popupMB: <mx:PopUpMenuButton id="popupMB" 3. Specify the data source for the PopUpMenuButton control as {fileMenuChoices} by

setting the dataProvider property: dataProvider="{fileMenuChoices}" 4. Cast the PopUpMenuButton control’s popUp property to a Menu and select the second

item as the default: Menu(popupMB.popUp).selectedIndex=2; 5. Use the label property of the PopUpMenuButton control to set the main button label:

labelField="@label"

CAUTION Use the PopUpMenuButton’s creationComplete event to set the main button label from the data provider.

The completed code should look like Listing 4-5. Listing 4-5 Create a PopUpMenuButton control <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.controls.Menu private function initMenuData():void { Menu(popupMB.popUp).selectedIndex=2; } ]]> </mx:Script>

111


112

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

<mx:XML id="fileMenuChoices" format="e4x"> <root> <fileItem label="New"/> <fileItem label="Open"/> <fileItem label="Save"/> <separator type="separator"/> <fileItem label="Exit"/> </root> </mx:XML> <mx:PopUpMenuButton id="popupMB" showRoot="false" labelField="@label" dataProvider="{fileMenuChoices}" creationComplete="initMenuData();"/> </mx:Application>

Define the data source using an XML component.

Call the initialization function to set the default selection.

Figure 4-13 The PopupMenuButton when clicked

When the application runs, it displays like Figure 4-13.

Running Your Applications After your projects are built, you may run and debug them as applications to test their functionality. Running and debugging your projects opens the main application SWF file in your default web browser or directly in Flash Player. Your applications run based on a


Chapter 4:

Working with Flex Builder

launch configuration. When you create new Flex and ActionScript applications, a launch configuration specifies the location of the built applications files, the main application file, and so on. In most cases the default launch configuration is all youâ&#x20AC;&#x2122;ll need to run and debug your applications. You can, however, modify the launch configuration or create custom launch configurations. In Chapter 5 youâ&#x20AC;&#x2122;ll learn how to use states, transitions, effects, and behaviors.

113


This page intentionally left blank


Chapter

5

States, Transitions, and Behaviors

115


116

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

States and Transitions

Creating States

Effects and Transitions

Triggers

Creating Behaviors

Composite Effects

Binding Variables

I

n Flex there are states and transitions. A state is a named structure that contains modifications to the visual presentation of components, while a transition is a grouping of various different elements, such as a fade. States can be created using MXML or ActionScript but are inherently easier to create with MXML. Any effect that’s supported by Flex can be part of a transition. You can define several states for an application or component, but only one state can be active at once. Once a new state is created, you can modify it by using the State pane and modify, add, or delete your desired components. You can use states to set up properties, modify the style of components within the state, and modify the event handler of an enclosed component. States do a whole lot of different things in Flex, and you can use numerous different tags to create the kind of effects, properties, and styles you want for your user to see in your application. Then there are effects and transitions. Effects are changes to the visual presentation of an object or sometimes a sound. Effects operate for a predetermined duration. Examples of Flex effects include fades, motion, shrinking, and growing. When an effect is paired up with a change of state, it’s called a transition. Transitions apply their effects to one or more components. A transition in your application, for example, between one screen that fades to the background and new information that displays is as important as transitions between paragraphs. Triggers are the hooks that launch code based on an event. The trigger may be based on a user action such as clicking a button or the logic in your application. They differ from


Chapter 5:

States, Transitions, and Behaviors

transitions in that they’re not created to respond to a change of state. Some cool triggers are: causing an effect on a control, causing an effect to become visible or invisible, or causing an effect when the mouse interacts with a component. Another aspect is behaviors, which can be created using MXML or ActionScript code. The creation process for effects creates an instance of the effect’s class automatically. You’ll have to define one effect in order to use the behavior and then associate it with an event. It’s also possible to launch behaviors from Flex Events. These events provide an easy way to launch a behavior and an alternative to using component triggers. When you use Flex Events, it’s possible to invoke a behavior on a different component than the original one. Binding variables means that Flex adds a trigger that fires when the value of the source variable changes and notifies components bound to the value to update. Luckily, there is a Flex standard, which has components already defined with properties that are bindable. Those values can be referenced as bound variables without any extra work. You will declare and reference bound variables. Working with bound data and states addresses customizing the data and which components appear in your applications.

States and Transitions A Flex state is a named structure that contains modifications to the visual presentation of components. A state can hold both changes to components and child states, such as a hierarchy. The component changes apply when the state becomes active. If the parent of a child state is made active, all the changes in the child states also apply. States provide an organizational tool for making changes to a group of components. They make switching tasks or revealing more information easier within your application given a user’s input. ActionScript or MXML define states, which are referenced by their name. Applications can have several view states with a component belonging to more than one state. Every Flex application has at least one state called the base. The base is the default state. You define states in order to manage the layout of your page information based on the current user task. This is a way for you to keep track of your application’s layout. Transitions are a grouping of effects such as fades. They make switching states more visually appealing. For example, when the user triggers a state change, a transition makes the change from the first state to the second one. For example, if you sent an e-mail from your Flex application, the composition window could fade out and the list of messages then fade in. If there weren’t a transition, all changes from one state to another would happen simultaneously.

117


118

Flex 3: A Beginner’s Guide

Transitions are similar to using a ViewStack navigator container to show or hide related content based on a user’s selection. But, transitions provide more flexibility than a ViewStack navigator when defining which elements display. Any effect that’s supported by Flex can be part of a transition.

Creating States Although states can be created using ActionScript, they’re generally easier to create with MXML, since they work with the presentation of components, and that’s what MXML is well suited for. States may be created at the application level or at the component level. Figure 5-1 shows the Flex Builder States pane. This pane is only available in the design editing mode. The current active state is highlighted in the States pane. To create a new state, click the New icon. Select a name that represents the state’s functionality.

Apply States You can define several states for an application or component, but only one state can be active at once. The state is set using the currentState property of a component. The state is often changed in response to a user action; for example, clicking a button or a link. The button’s base state can be set to change an object group based on the user’s click event. New

Edit Delete

Figure 5-1 The Flex Builder States pane with the base state


Chapter 5:

States, Transitions, and Behaviors

The base state contains components that are used by all of the application states. Once a new state is created, you can modify it by using the States pane and modify, add, or delete your desired components. The new state can also change component attributes such as size and position. During program runtime when the new state is selected, the components jump to the new locations and attribute values unless you’ve specified a transition to soften the switch. In the following example there are two states created in addition to the base state. They’re Check and Charge. The current base state has a radio group. Each radio group entry applies one of the states, so since the Check and Charge states automatically inherit the radio group from the base state, it’s not removed when either state is selected. However, selecting the base state removes any components added to the children’s states. The <mx:AddChild> tag is used to assign states in MXML. By default it adds the child state to the container or component where the state’s defined, but the parent state can be specified. To specify a parent state, use the relativeTo attribute of the <mxAddChild> tag. The following example sets the relativeTo field to {form1}, since the state definition wasn’t made within the form. Therefore the children’s state uses form1 as their parent state. For example, to create a form that changes the payment type fields based on a RadioButtonGroup, you’d enter the following code: Listing 5-1 Create a Form that Changes Payment Type <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:states> Creates the Charge state. <mx:State name="Charge"> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Charge Number" id="formitem1"> <mx:TextInput/> </mx:FormItem> </mx:AddChild> <mx:AddChild relativeTo="{formitem1}" position="before"> <mx:FormItem label="Name"> <mx:TextInput/> </mx:FormItem> </mx:AddChild> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Expiration Date"> <mx:DateField/> </mx:FormItem>

119


120

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

</mx:AddChild> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Submit"> <mx:Button label="Button" click="currentState=''"/> </mx:FormItem> </mx:AddChild> </mx:State> <mx:State name="Check"> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Routing Number"> <mx:TextInput/> </mx:FormItem> </mx:AddChild> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Account Number"> <mx:TextInput/> </mx:FormItem> </mx:AddChild> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Submit"> <mx:Button label="Button" click="currentState=''"/> </mx:FormItem> </mx:AddChild> Selects Check as </mx:State> the current state </mx:states> when this radio <mx:Form x="103" y="56" width="397" height="219" id="form1"> button is selected. <mx:RadioButtonGroup id="radiogroup1"/> <mx:RadioButton x="143" y="70" label="Check" groupName="radiogroup1" click="currentState='Check'"/> <mx:RadioButton x="143" y="94" label="Charge" groupName="radiogroup1" click="currentState='Charge'"/> </mx:Form> </mx:Application>

Listing 5-1 can be created from Flex Builder, and parent elements are mx:states instead of mx:States. The application initially appears as Figure 5-2. Once the user selects Check, the Routing Number and Account Number fields display. The button also becomes visible as seen in Figure 5-3. If the user clicks Charge instead, the Name, Charge Number, and Expiration Date fields display similar to Figure 5-4. If the Submit button is selected, the user is returned to the default state that only displays the payment type radio group.


Chapter 5:

States, Transitions, and Behaviors

Figure 5-2 Only the Payment Type radio group displays

Figure 5-3 The Check Fields display

121


122

Flex 3: A Beginner’s Guide

Figure 5-4 The Charge Fields display

Ask the Expert Q: A:

Do bookmarks from the web browser work as expected when running a Flex application? What about the back and forward buttons? Because the browser bookmarks are based on the page’s URL, and Flex applications don’t automatically change the URL between states, traditional bookmarking doesn’t work. The same goes for using the back and forward buttons with the back button typically navigating away from the Flex application altogether. In Flex 2, a third-party package called urlkit (http://code.google.com/p/urlkit/downloads/ list ) was developed to solve this problem. Flex 3 includes this functionality as part of the core Flex offering and calls it Deep Linking. The method Flex 3 uses works so well that urlkit now uses the Flex 3 Deep Linking as the basis of its technique.


Chapter 5:

States, Transitions, and Behaviors

Deep Linking requires a modern web browser such as FireFox, Safari, or Internet Explorer version 6 or later with scripting enabled. Which states of the application can be bookmarked and navigated must be selected when developing the application such as a login states versus states that represent viewing individual media assets. The Flex class BrowserManager manages the communication between the browser and the Flex application about what state the application is in (and therefore the URL to be bookmarked) and if the user has selected a navigation button. For more detailed information on using the BrowserManager class, visit http://livedocs.adobe.com/labs/flex3/html/help.html?content= deep_linking_1.html.

Properties As mentioned earlier, states can set the properties of contained components. To set a property from a state, use the <mx:SetProperty> MXML tag. Nested within an <mx:State> tag, it takes the target, name, and value attributes to set the appropriate property. The target attribute specifies the component to modify. The name field specifies the property to set for that component, while the value specifies the value of the property.

Styles A state can also modify the style of components within the state. Remember that styles control how the component displays, such as the text color and font. To modify the styles, use the MXML tag <mx:SetStyle>. Like the <mx:SetProperty> tag, the <mx:SetStyle> tag takes a target, a name, and a value as its parameters. The target attribute specifies the component to modify. The name field specifies the style to set for that component, while the value specifies the attribute value of the style. For example, to set the CSS value font-family=serif, you would use the following code: <mx:SetStyle target="{Button}" name="font-family" value="serif"/>

Event Handlers States can also modify the event handler of an enclosed component using the <mx:SetEventHandler> tag. Like the style and property MXML tags, it takes a target, a name, and an attribute. In this case, the target is the component, the name is the event handler to modify, and the attribute is the new event handler.

123


124

Flex 3: A Beginner’s Guide

NOTE It’s best to only use states that modify your application’s view. While it’s possible to modify the logic of your application based on states, it should be avoided.

Effects and Transitions Effects are changes to the visual presentation of an object or sometimes a sound. Effects operate for a predetermined duration. Examples of Flex effects include fades, motion, shrinking, and growing. While effects don’t change the base functionality of an application, they can both improve the look of an application and help guide a user to the relevant portion of a screen. Like any good thing, they shouldn’t be overused or they lose their benefit to the user. When an effect is paired up with a change of state, it’s called a transition. Without transitions, changes of state in an application happen instantaneously. A smooth transition, such as a fade, can help the user to understand what changes are happening as the state changes. Important components can be emphasized as part of the transition, making the application easier to use. Common Flex effects are listed in Table 5-1. It’s time to put states and effects together to create a transition.

Effect

Description

Fade

Fades move between being totally opaque or transparent.

Move

The effect moves on the screen to different places.

Pause

Between your effects, pauses are inserted.

Resize

This changes the width and height of a component over a specific time interval.

Wipe

Displays or removes a component that moves from the left, right, top, or bottom.

Zoom

A component zooms in or out from its center point, over a period of time.

Table 5-1 Flex Effects and Purposes


Chapter 5:

States, Transitions, and Behaviors

Creating a Transition Building on the payment form example referenced in Figure 5-2, weâ&#x20AC;&#x2122;ll create a transition between states: 1. Create a new MXML Application in Flex Builder called Transition.mxml. 2. The application must have more than one state, the base state, to do a transition. Listing

5-1 has two states, Check and Charge. 3. Create the transition by defining an MXML block in the source view of the application.

Use the parent tag <mx:Transitions> and at least one <mx:Transition> child tag to define the transition: <mx:Transitions> <mx:Transition id="paymentTransition"> </mx:Transition> </mx:Transitions>

NOTE Multiple effects can be added to a transition by including more than one <mx:transition> tag. The effects run sequentially or in parallel, depending on the tag used.

4. Specify the fromState and toState properties for when a transition activates: <mx:Transitions> <mx:Transition id="paymentTransition" fromState="*" toState="Charge"> </mx:Transition> </mx:Transitions>

The fromState and toState properties for the <mxTransition> tag specify when a transition should be performed. The asterisk (*) wildcard character matches any state, so specifying fromState=* matches coming from any state. Likewise, the toState property can take the wildcard or the name of a state. A transition only applies to a change of state if both the fromState and toState properties match the change of states. Once youâ&#x20AC;&#x2122;ve created an <mx:transition> MXML block, the specific transition(s) to run and the order in which they run are specified using either the <mx:parallel> or <mx:sequence> tags. If the effects run all at once, use the <mx:parallel> tag. To

125


126

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

run the effects one after another in the order you define them, use the <mx:sequence> tag. This example code defines a parallel block for running events: <mx:Transition id="paymentTransitionCharge" fromState="*" toState="Charge"> <mx:Parallel> </mx:Parallel> </mx:Transition>

A transition applies its effects to one or more components. If the transition applies to only one component, use the target property of the <mx:Parallel> or <mx:Sequence> tags to specify the target. If it applies to more than one component, use the targets property set to an array of the components to modify. The following example specifies the targets as formitem1, formitem2, formitem3, and formitem4. <mx:Transitions> <mx:Transition id="paymentTransitionCharge" fromState="*" toState="Charge"> <mx:Parallel targets="{[formitem1,formitem2,formitem3,formitem4]}"> </mx:Parallel> Defines the array of targets for this transition. </mx:Transition> </mx:Transitions>

The effects to play are specified as child tags within either the <mx:Parallel> or <mx:Sequence> tags. <mx:Transitions> <mx:Transition id="paymentTransitionCharge" fromState="*" toState="Charge"> <mx:Parallel targets="{[formitem1,formitem2,formitem3,formitem4]}"> <mx:Fade duration="400"/> These effects run in <mx:Move xFrom="0" yFrom="0" duration="400"/> parallel during the </mx:Parallel> transition. </mx:Transition> </mx:Transitions>

5. Enter this code into the source view of the editor: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:states> <mx:State name="Charge"> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Charge Number" id="formitem1"> <mx:TextInput/> </mx:FormItem> </mx:AddChild> <mx:AddChild relativeTo="{formitem1}" position="before"> <mx:FormItem label="Name" id="formitem2"> <mx:TextInput/> </mx:FormItem> </mx:AddChild>


Chapter 5:

States, Transitions, and Behaviors

<mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Expiration Date" id="formitem3"> <mx:DateField/> </mx:FormItem> </mx:AddChild> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Submit" id="formitem4"> <mx:Button label="Button" click="currentState=''"/> </mx:FormItem> </mx:AddChild> </mx:State> <mx:State name="Check"> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Routing Number" id="formitema"> <mx:TextInput/> </mx:FormItem> </mx:AddChild> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Account Number" id="formitemb"> <mx:TextInput/> </mx:FormItem> </mx:AddChild> <mx:AddChild relativeTo="{form1}" position="lastChild"> <mx:FormItem label="Submit" id="formitemc"> <mx:Button label="Button" click="currentState=''"/> </mx:FormItem> </mx:AddChild> </mx:State> </mx:states> <mx:transitions> <mx:Transition id="paymentTransitionCharge" fromState="*" toState="Charge"> <mx:Parallel targets="{[formitem1,formitem2,formitem3,formitem4,formitema,formitemb,formitemc]}"> <mx:Fade duration="400"/> <mx:Move xFrom="0" yFrom="0" duration="400"/> </mx:Parallel> </mx:Transition> <mx:Transition id="paymentTransitionCheck" fromState="*" toState="Check"> <mx:Parallel targets="{[formitema,formitemb,formitemc]}"> <mx:Fade duration="400"/> <mx:Move xFrom="0" yFrom="0" duration="400"/> </mx:Parallel> </mx:Transition> </mx:transitions> <mx:Form x="103" y="56" width="397" height="284" id="form1"> <mx:RadioButtonGroup id="radiogroup1"/> <mx:RadioButton x="143" y="70" label="Check" groupName="radiogroup1" click="currentState='Check'"/> <mx:RadioButton x="143" y="94" label="Charge" groupName="radiogroup1" click="currentState='Charge'"/> </mx:Form> </mx:Application>

127


128

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

6. Click the Run Transitions entry from the Flex Builder Run menu to test the application.

If you have not already saved the file, do so when prompted. 7. The application displays in the default browser. 8. To verify the transition, select the Check or Credit radio button to switch application states.

Initially, the only displayed item on the screen is the payment type check boxes. When the user selects a check box, the appropriate components for that state gradually fade onto the screen. Figure 5-5 shows the application while switching from Check to Credit states. Flex behaviors are the linking of an effect to your application based on a triggering event.

Triggers A trigger is the hook that launches code based on an event. The trigger may be based on a user action such as clicking a button or the logic in your application. They differ from transitions in that theyâ&#x20AC;&#x2122;re not created to response to a change of state. Table 5-2 lists common Flex triggers and what causes them to trigger, also known as firing.

Figure 5-5 The Payment application during a state change


Chapter 5:

States, Transitions, and Behaviors

Trigger Name

Fires on

focusInEffect

Causes an effect on a control.

focusOutEffect

Causes an effect on a control.

hideEffect

Causes the effect to become visible or invisible.

mouseOverEffect

Causes an effect when the mouse interacts with the component.

mouseOutEffect

Causes an effect when the mouse interacts with the component.

mouseDownEffect

Causes an effect when the mouse interacts with the component.

mouseUpEffect

Causes an effect when the mouse interacts with the component.

moveEffect

Causes an effect when its associated component moves.

resizeEffect

Causes an effect when its associated component is resized.

showEffect

Causes an effect when its associated component displays.

Table 5-2 When Flex Triggers Fire

Creating Behaviors Behaviors can be created using MXML or ActionScript code. The creation process for an effect creates an instance of the effect’s class automatically. You’ll have to define one effect in order to use a behavior and then associate it with an event. Usually the event is linked to a user’s action on a component. It’s possible to play more than one effect simultaneously or in sequence for a single behavior. A behavior can be defined using this code: <mx:Fade id="editorFade" alphaFrom="0" alphaTo="1" duration="2000"/>

Then launch it from an effect event. To see a list of Events for a component, select the Effects listing from the Flex Builder Properties panel while in the Category View mode as shown in Figure 5-6. To launch an effect from the component’s definition, specify the effect’s name as a property during the definition of the component. Set the property value to the event ID enclosed in curly brackets ({}). For example, in order to set a button to use the Fade

129


130

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Click here to select Category view.

Figure 5-6 The Effect Properties panel listing for a button

effect defined in the last code snippet above in response to a mouse rollover event, use this MXML: <mx:Button label="Button" rollOverEffect="{editorFade}" />

Or to activate the behavior on the showEffect effect, use the following code: <mx:Button label="Button" showEffect="{editorFade}" />

NOTE The curly brackets ({}) are optional, as the code works with or without them.


Chapter 5:

States, Transitions, and Behaviors

It’s also possible to launch behaviors from Flex Events discussed in the next section. It’s important to realize that the two calling formats can be easily mixed up and cause your code to not work. When using an event from a component’s event list, always use the curly braces and your effect’s ID. The calling syntax in the next section doesn’t use the curly brackets; instead, it calls the Effect’s play method.

Invoke Using Flex Events Flex Events provide an easy way to launch a behavior and an alternative to using component triggers. When you use Flex Events, it’s possible to invoke a behavior on a different component than the original one. For example, you can cause a RichTextEditor component to fade in when a button is clicked.

Try This

Fading in a RichTextEditor with a Button Click

The following steps walk you through the process of using a behavior to fade in a RichTextEditor: 1. Create a new MXML application called ButtonBehavior.mxml. 2. Select Design mode and insert a Button toward the top-left corner of the design panel

by dragging it from the Controls list. The exact location doesn’t matter, so it’s okay if the x and y parameters are different in your MXML code than in the example. 3. Insert a RichTextEditor component next to the button. 4. Set the ID property of the RichTextEditor to richText1 in the Property panel’s Common

section. This allows specifying this component’s ID when defining the behavior. 5. Switch to Source mode. The effect must be entered as MXML. 6. Enter the following to define the Fade effect from transparent to opaque before the

button’s definition: <mx:Fade id="editorFade" alphaFrom="0" alphaTo="1" duration="2000"/>

(continued)

131


132

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

7. Add a target property to the Fade effect using the target property. It specifies the target

as richText1 similar to this code: <mx:Fade id="editorFade" target="{richText1}" alphaFrom="0" alphaTo="1" duration="2000"/>

8. Modify the <mx:Button> tag to specify the editorFade effect to play in response to

a click event, as shown in the code shown next. Additionally, add the bolded code in the examples to the /<mx:Button>/ tag to specify the /editorFade/ effect to play in response to a click event: <mx:Button label="Button" click="editorFade.play()"/>

9. Since the RichTextEditor should be hidden when the application first starts, set its

visible property to false using the bolded code: <mx:RichTextEditor x="152" y="50" id="richText1" visible="false"> </mx:RichTextEditor>

10. In order to reveal the RichTextEditor when the user clicks the button, add the bolded

text to the button definition: <mx:Button label="Button" click="editorFade.play();richText1.visible=true"/>

11. The code in your Source view should now look like this: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Fade id="editorFade" target="{richText1}" alphaFrom="0" alphaTo="1" duration="2000"/> <mx:Button label="Button" click="editorFade.play();richText1.visible=true"/> <mx:RichTextEditor x="80" y="0" id="richText1" visible="false"> </mx:RichTextEditor> </mx:Application>

Note, the URL in this code is only a unique identifier and not an active web address. 12. Select Run ButtonBehavior from the Flex Builder Run menu. Save the file if prompted.

The application will then launch in the default browser. When the Button is clicked, the click event calls the Fade effect as shown, mid-fade, in Figure 5-7.


Chapter 5:

States, Transitions, and Behaviors

Figure 5-7 The ButtonBehavior application after clicking the button

Notice that the fade effect happens to a different component, the RichTextEditor, rather than the component that had the click event.

Composite Effects A behavior can have a single effect or a composite effect. A composite effect is more than one effect that occurs when you trigger a behavior. For example, a component can simultaneously move and fade. The same MXML tags are used to define how effects work when defining transitions. Theyâ&#x20AC;&#x2122;re the <mx:Parallel> and <mx:Sequence> tags that execute an effect simultaneously and one after the other, respectively. Remember that the <mx:Sequence> tag performs the effects in the order that you define them.

133


134

Flex 3: A Beginner’s Guide

The following example can be modified to do two effects: Listing 5-2 RichTextEditor with a Composite Effect <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Parallel id="editorFadeMove" target="{richText1}"> <mx:Fade id="editorFade" Begins the alphaFrom="0" composite effect alphaTo="1" with the id duration="2000"/> editorFadeMove. Calls the composite effect <mx:Move id="numbersMove" yBy="20" duration="2000"/> instead of a single effect. </mx:Parallel> <mx:Button label="Button" click="editorFadeMove.play();richText1.visible=true"/> <mx:RichTextEditor x="80" y="0" id="richText1" visible="false"> </mx:RichTextEditor> </mx:Application>

Notice that the two effects are defined within a <mx:Parallel> tag so the Fade and Move effects execute at the same time when the user clicks the button. The only change that needs to be made to the button is to change the click handler to call editorFadeMove instead of the old single effect. The <mx:Sequence> tag could have been used to play the effects sequentially.

Binding Variables When specifying a variable as a source for a component, Flex allows specifying that if the value of the variable changes, the component using the variable should also update. This process is called binding variables. What’s actually happening behind the scenes is that Flex is adding a trigger that fires when the value of the source variable changes and notifies any components bound to the value to update. This is a nice feature of Flex and one that isn’t found in many other programming environments, where the developers are left to create the trigger themselves.

Declaring When using a bound variable, there are two steps to the process. The first step is that the source variable must be declared as bindable using the MXML metatag [bindable]. The Flex standard components already define their properties as bindable. That means that those values can be referenced as bound variables without any extra work. For example, to define a variable called dispTemp: [Bindable] private var dispTemp:Number = 72;


Chapter 5:

States, Transitions, and Behaviors

This tells the compiler that the value in the variable can be mapped to a property like Label.text and to create a trigger that updates any mapped component when the variableâ&#x20AC;&#x2122;s value changes. The [Bindable] declaration comes directly before the variable that is bound. The syntax for declaring the variable is otherwise not different from any other declaration. Now all thatâ&#x20AC;&#x2122;s needed is to specify a variable that is bound when using it in the component.

Referencing To specify that a variable is a bound variable use the curly braces ({}) when referencing the variable. For example, to reference dispTemp: <mx:Label id="lblOutput" text="{String(dispTemp)}"/>

This code tells Flex Builder to use the bound variable dispTemp as the source for the label text. Any changes to the value of the variable immediately update in the component.

NOTE Flex allows placing ActionScript within the curly braces when referencing a bound variable. This opens up many possibilities for messaging the value of the variable before sending it to the component.

The following example creates a label with a bound variable called dispTemp associated to its text property. Two functions to do temperature conversion are also created, as well as a button to launch each function. Listing 5-3 dispTemp Bound Variable <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ [Bindable] private var dispTemp:Number = 72; private var sourceFTemp:Number = 72; private function goFahrenheit():void { dispTemp = sourceFTemp; }

135


136

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

private function goCelsius():void { dispTemp = (5/9) * (sourceFTemp - 32); } ]]> </mx:Script> <mx:Panel x="10" y="10" width="200" height="250" layout="absolute" title="Temp Conversion Binding"> <mx:VBox x="10" y="10" height="100%"> <mx:Label id="lblOutput" text="{String(dispTemp)}"/> <mx:Button label="Change Fahrenheit" id="bChangeF" click="{goFahrenheit()}"/> <mx:Button label="Change Celsius" id="bChangeC" click="{goCelsius()}"/> </mx:VBox> </mx:Panel> </mx:Application>

Figure 5-8 The temperature displays in Celsius


Chapter 5:

States, Transitions, and Behaviors

Flex Builder also has a tag called <mx:Binding> that specifies a source and a destination for a binding relationship. This is handy for binding one UI component to another. We donâ&#x20AC;&#x2122;t have to use curly brackets ({}) inside the source and destination attributes, because there is an expectation that there is already a variable/property there. Youâ&#x20AC;&#x2122;ll see the source is curSlider.value, which tells the compiler we want to bind the value in our text field to our destination sourceCTemp. This is called backward data binding. Then the variable binds to the label, using the same approach as we used in the preceding example. In Listing 5-3, the current value of a HSlider is bound using <mx:Binding> to a variable containing the current temperature in Celsius. This variable is in turn displayed in text labels for both Fahrenheit and Celsius. Listing 5-4 Fahrenheit and Celsius Text Label <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ [Bindable] private var sourceCTemp:Number; ]]> </mx:Script> <mx:Binding source="curSlider.value" destination="sourceCTemp" /> <mx:Panel x="10" y="10" width="300" height="250" layout="absolute" title="Temp Coversion Binding"> <mx:VBox x="10" y="10" height="100%"> <mx:Label id="dispF" text="{'Celsius:' + String(sourceCTemp)}"/> <mx:Label id="dispC" text="{'Fahrenheit:' + String((9/5) * sourceCTemp + 32)}"/> <mx:HSlider id="curSlider" minimum="0" maximum="100"/> </mx:VBox> </mx:Panel> </mx:Application>

137


138

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 5-9 The temperature display with the slider set to 50 degrees Celsius using <Mx:Binding>

Working with bound data and states addresses customizing the data and which components appear in your applications. The next chapter discusses customizing the look of your applications through skinning components.


Chapter

6

Modifying Your Applicationâ&#x20AC;&#x2122;s Appearance

139


140

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

Categories of Customization

Styles and Skins

Themes

Skins

T

he great thing about Flex is that if you don’t like the default look of a Flex application, you can customize it in any number of ways. You can start by modifying something simple, perhaps your application’s color scheme, and then branch out to changing the sizes of text and fonts. Flex uses some of the same concepts to modify the look and feel that HTML does, such as Cascading Style Sheets (CSS), but you can also use skins and themes. Additionally, instead of hard-code MXML editing, you can edit your designs and layouts with the various Design view enhancements. Flex Builder 3 extends the concept of being able to edit your file both in Source and Design views to CSS files. Flex uses CSS files like HTML does, to maintain a collection of style information in one file. When viewing a CSS file in Design mode, supported style properties can be modified using the Property Inspector. The visual representations of the various states of a component, as modified by the CSS, are also displayed in the Design window. There are also collections of styles, graphical assets such as images, and skins. They define the Flex application’s appearance. They can modify as many properties as you like, from basics such as color to more advanced options like constraints. Enhanced constraints allow you to have more complex resizable layouts. Some of these enhancements include application, canvas, module, and panel. The default theme for Flex is called Halo, but it also allows you to assign predefined colors like red and green to the CSS properties and includes haloBlue (the default), haloOrange, haloGreen, and haloSilver as ready-to-use colors. Styles can be set up using inline styles or local style definitions. An easy way to find out what style properties can be set for a component is to use the Adobe Flex Style Explorer. The Flex Style Explorer is a Flex application that lists all of the Flex components in a tree view on the left-hand side of your window and has a pane for setting the style values and a sandbox pane that shows how the style looks when applied to that component. It’s accessible from the Start page of Flex Builder.


Chapter 6:

Modifying Your Application’s Appearance

Flex allows mapping skins to controls using images of your choice. Skins may be defined either using graphic images, called graphical skinning, or by defining the skin using code, called programmatic skinning. You can use different skins to reflect the different states of a component. Some common states related to interaction with the user make sense to skin, such as mouse over, mouse down, and mouse off states.

Categories of Customization Flex does a great job at splitting out the presentation of your application from the working application logic. If you don’t like the default look of a Flex application, you can customize it in practically an infinite number of ways. You start by modifying something simple, perhaps your application’s color scheme, and then branch out to changing the size of text and fonts. Flex builder uses some of the same concepts to modify the appearance of an application that a regular web page uses, such as styles and CSS, and it also adds its own organizational tools for appearance modification, called skins and themes.

Styles and Skins Styles are the visual properties of components such as the size of the text in a RichTextEditor or the color of the background in an Accordion control. Some styles can inherit from a parent container or class. Inherited styles can be overridden at the component level. They can also be applied to a group of components all at once, which makes creating a uniform look easier when you develop an application. Styles specify their values as colors, duration, or length. With the Skin Importer you can select an image from a folder or directory that is an SWF/SWC file and then import that image into your Flex project by mapping the assets to skin elements found in the Flex 3 SDK components. The Import Wizard is easy to use and presents all assets and mapping to your component skinning elements. There are numerous enhancements with this version of Flex: ●

Graphical border skins now use the scale9Grid property for all borderMetrics.

There are skins for the elements within DataGrid.

There are PanelSkin programmable skin classes.

The ProgressBar lets you perform skinning using the maskSkin.

You have the ability to rapidly skin your components, lay out your application with incredible pixel accuracy, and instead of hard-code MXML editing, edit your designs and layouts with the various Design view enhancements.

141


142

Flex 3: A Beginner’s Guide

You can use a CSS to set style properties, but not all style properties can be set doing this. For example, properties such as height and width are set via the UIComponent class and therefore cannot be set using CSS. CSS also uses inheritance within the CSS definition to simplify applying the same settings to multiple components in the CSS.

Enhanced Constraints As discussed in Chapter 4, constraints define how an application places components as the screen first appears or is resized. Flex 3’s enhanced constraints improve Flex 2’s constraints layout system by allowing more complex resizable layouts. The enhanced containers are: ●

Application

Canvas

Module

Panel

These containers can be partitioned with ConstraintColumns and ConstraintRows absolute positioning constraints. They constrain child containers into rows and columns much like an HTML table. This allows the sizing to be relative to the other children in the container instead of Flex 2’s sizing relative to the parent container. ConstraintRows and ConstraintColumns are layout-only controls because they don’t actually display anything on the screen but affect the layout of other visible controls. They are only added to absolute positioning containers, such as a Canvas or a Panel, to divide up its space. Controls within either a ConstraintRows or ConstraintColumns constraint can position themselves relative to the parent container or the ConstraintRow/ConstraintColumn. Similar to HTML tables, ConstraintRows and ConstraintColumns have three different sizing options.

Fixed Sizing Fixed-sized ConstraintRow/ConstraintColumn constraints use a predefined pixel size. For example, to specify a ConstraintColumn with a fixed size of 80, you would use this code: <mx:ConstraintColumn

id="fixedcol" width="80" />

While the parent container may become larger or smaller, the Constraint column remains fixed at a width of 80 pixels. This also means that the parent container cannot become smaller than 80 pixels.


Chapter 6:

Modifying Your Application’s Appearance

Percentage Sizing Percentage-sized ConstraintRow/ConstraintColumn constraints use a relative, percent-based size. The size is relative to the parent container. In HTML percentage-based columns are relative to the size of the table as a whole. For example, to specify a ConstraintColumn with a relative size of 80 percent, you would use this code: <mx:ConstraintColumn

id="relcol" width="80%" />

As the parent container changes size, the column also changes size proportionately.

Content Sizing Content-sized ConstraintRow/ConstraintColumn constraints base the size of the row or column on the content. In HTML, a content-based column is the default if a relative or fixed size is not supplied. Likewise, Flex defaults to a content-sized column or row if neither a relative nor a fixed-width property is specified. For example, to specify a ConstraintColumn with content sizing, you’d use the following code: <mx:ConstraintColumn

id="contentcol" />

The contentcol column is going to be as wide as the largest child.

Specifying Size Limits Maximum and minimum thresholds can also be set for the size of ConstraintRow/ ConstraintColumn constraints. Obviously, this doesn’t apply to the fixed-size modes, so only percentage and content sizing make sense for specifying minimum and maximum size limits.

Positioning from the Parent or the ConstraintColumn/ConstraintRow As mentioned earlier, it’s possible to position a control that’s part of a ConstraintColumn or ConstraintRow relative to the ConstraintColumn/ConstraintRow or the parent container or the column/row. The control can even be set relative to another ConstraintColumn/ConstraintRow. An offset can be specified from the left, right, or center of the referenced control. When specifying an offset from anything but the parent container, specify the id of the container you want to offset from by placing the id and a colon (:) before the offset. For example, to place a CheckBox 5 pixels from the top of the parent container, you’d use this code: <mx:CheckBox id="cbox" top="5"/>

To place the CheckBox 5 pixels from the top of a ConstraintRow with the id of const_row, you can use the following code: <mx:CheckBox id="cbox" top="col1:10"/>

143


144

Flex 3: A Beginner’s Guide

NOTE The Enhanced Constraint feature effectively replaces the functionality of the older Grid container when building tabular-style resizable layouts.

CSS Property Inspector Flex Builder 3 extends the concept of being able to edit your file both in Source and Design views to CSS files. Flex uses CSS files like HTML does, to maintain a collection of style information in one file. When viewing a CSS file in Design mode, supported style properties can be modified using the Property Inspector. The visual representations of the various states of a component, as modified by the CSS, are also displayed in the Design window. Not all components may be supported for viewing in the CSS Property Inspector, but at least the following are supported: ●

Button

Containers (including Application, Canvas, and VBox)

Label

Lists (including List, DataGrid, and TileList)

If you’re editing a new CSS file, you’ll need to manually add a style definition before being able to modify the style using the Property Inspector. This can be as simple as adding this code to the CSS file: Button { }

Once switched to Design mode, the various states of the button appear and any changes are automatically made to the source of the CSS file. The layout of the Property Inspector is very similar to the layout you see when modifying component styles in MXML mode. Figure 6-1 shows the CSS Properties Inspector for a CSS file that’s used later on in this chapter. It contains Button style definitions.

Property Inspector Styling Improvements For editing both CSS styles and components there are several new improvements to the Property Inspector in Flex 3. Selecting colors now launches a color selector that allows


Chapter 6:

Modifying Your Applicationâ&#x20AC;&#x2122;s Appearance

Figure 6-1 The CSS Property Inspector with a button selected in the outline

you to enter hex or RGB values in addition to making a selection from a color spectrum. Previews of gradients are now available when you modify components that support them, including transparency (alpha). Font handling is also enhanced to allow for underlining. There is also a setting for font color options for multiple states when editing CSS styles such as mouse over or selected. Font typeface handling has been enhanced to allow for TrueType fonts when modifying a CSS style in the Property Inspector.

Themes Themes are collections of styles, graphical assets such as images, and skins. They define the Flex applicationâ&#x20AC;&#x2122;s appearance. They can modify as many properties as you like, from basics such as color to more advanced options like constraints.

145


146

Flex 3: A Beginner’s Guide

A quick and easy way to change the appearance of a Flex application is to download a theme from the Internet. Sites such as Scale Nine (www.scalenine.com) provide links to available themes. Themes come in two formats: ●

A single compiled SWC file

A CSS file and optionally a background image and an SWF file

A theme can be applied to an application by using the <mx:Style> tag. The tag takes the path to the theme’s CSS file as source. For example, to specify a theme called windowsXP that has a CSS file named windowsXP.css, specify the following code: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Style source="windowsXP.css"/> <mx:RichTextEditor x="21" y="10"> </mx:RichTextEditor> </mx:Application>

This code displays a RichTextEditor control using the windowXP.css theme as shown in Figure 6-2.

Figure 6-2 The RichTextEditor with a Windows XP–inspired theme


Chapter 6:

Modifying Your Application’s Appearance

As in the preceding example, this line can be inserted into your MXML application in the Source view after the <mx:Application> tag. Generally the asset files that are associated with the CSS file should be placed in your project’s root directory. If you move an asset file such as an SWF to a different directory than holds the CSS file, you’ll need to modify the path in the CSS file. The default theme for Flex is called Halo and is defined from the default.css file. The source files for the included themes are located in the frameworks directory, which varies depending on which Flex installation is used but should be similar to C:\Program Files\Adobe\Flex Builder 3\sdks\2.0.1\frameworks\themes. Flex allows you to assign predefined colors like red and green to CSS properties. But Flex also includes four tantalizing colors that are ready to use: ●

haloBlue, which is the default

haloOrange

haloGreen

haloSilver Other themes included with Flex are shown in Table 6-1.

Theme

Files

Description

Aeon Graphical

AeonGraphical.css AeonGraphical.swf

This theme looks the same as the default Halo theme but is packaged with the source files to build the theme. Therefore it can serve as a starting point to build your own theme based on the look of Halo.

HaloClassic

haloclassic.swc

The Halo theme as shipped with versions of Flex before version 2.

Ice

Ice.css

A theme with cooler-looking colors, such as pastels.

Institutional

Institutional.css

An industrial-looking theme.

Smoke

Smoke.css smoke_bg.jpg

A smoky theme.

Wooden

Wooden.css wooden_bg.jpg

A wood grain and tone theme.

Table 6-1 Additional Themes Included with Flex

147


148

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

To use one of the themes from Table 6-1, follow these steps: 1. Start Flex Builder. 2. Open an application in Flex Builder. 3. Click the top level of the project in the Navigator pane. 4. Select Properties from the File menu. 5. Select the Flex Compiler section from the tree on the left side of the Properties

window. 6. At the end of the Additional Compiler Arguments field, add a -theme parameter to

specify the path to the included theme to use: -theme "C:\Program Files\Adobe\Flex Builder 3 beta 2\sdks\3.0.0\frameworks\themes\Institutional\Institutional.css"

The Properties dialog with the Institutional theme specified is shown in Figure 6-3.

Figure 6-3 The Properties dialog with the Additional Compiler Arguments set


Chapter 6:

Modifying Your Applicationâ&#x20AC;&#x2122;s Appearance

NOTE Depending on your operating system and specific Flex Builder installation, this path varies. If this directory cannot be found, searching for the file Institutional.css reveals the proper path and location.

7. Click OK. 8. Select Run application name from the Flex Builder Run menu, where application name

is the name of the application you opened in Step 1. 9. The application displays in your default browser like Figure 6-4. Figure 6-5 shows how

the application looked before the change.

NOTE Flex Builder may not reflect the new theme in the display window when using a different included theme, but the correct theme will display when the application runs.

Setting Styles There are several ways that styles and style properties can be defined in Flex.

Figure 6-4 The Institutional theme applied to a sample application

149


150

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 6-5 An application using the default theme

Inline Styles Styles can be defined inline much like HTML allows inline style definition. For example, HTML allows <span style="color:red">Some Red Text</span>

To specify the same style for Flex, use the following code: <mx:Text color="red" text="Some Red Text"/>

Local Style Definition Local style definitions separate the style definition from its immediate use. They work similar to HTMLâ&#x20AC;&#x2122;s <style> tag. A style can be applied to all instances of a component using a Type Selector style or just individual instances using a Class Selector style. For example, the following HTML defines font and color properties for form inputs as well as a specific font override for the customButtonStyle class:


Chapter 6:

Modifying Your Applicationâ&#x20AC;&#x2122;s Appearance

Listing 6-1 HTML for Font and Color Properties <html> <head> <style> input { font-family:Arial; font-size: 16px; color:#999999; } .customButtonStyle { font-family:Verdana; font-size:12px; color:#000000; } </style> </head>

Defines the name of the style that the following lines are associated with.

<body> <form name="testform"> <input type="button" value="regular button" /><br /> <input type="button" class="customButtonStyle" value="customButtonStyle button" /> This button uses the </form> properties set for inputs </body> without a style class. </html>

When you run this code in a web browser, the HTML produces a page similar to Figure 6-6. In Flex the syntax for setting the properties for the style is the same, but the <mx:Style> tag is used to begin the style definition instead of <style>: Listing 6-2 Flex Style Properties <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Style> Button { font-family:Arial;

151


152

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

font-size: 16px; color:#999999; } .customButtonStyle Set this button to use the { customButtonStyle instead font-family:Verdana; of the Button-wide style. font-size: 12px; color:#000000; } </mx:Style> <mx:Button label="regular button"/> <mx:Button label="customButtonStyle button" styleName="customButtonStyle" y="35"/> </mx:Application>

The MXML code produces output as shown in Figure 6-7 when executed by Flex. Notice that although there are minor differences in the look of the pages between HTML and Flex, the same text style effects are apparent in both screens. The compiler tag was taken out, so the colors in the examples are back to the default Flex colors. An easy way to find out what style properties can be set for a component is to use the Adobe Flex Style Explorer. The Flex Style Explorer is a Flex application that lists all of the Flex components in a tree view on the left-hand side of your window and has a pane for setting the style values and a sandbox pane that shows how the style looks when applied to that component. Itâ&#x20AC;&#x2122;s accessible from the Start page of Flex Builder by selecting Flex Start Page from the Help menu or at http://examples.adobe.com/flex2/consulting/ styleexplorer/Flex2StyleExplorer.html from a web browser. Figure 6-8 shows the Flex Style Explorer. Notice that the CSS window displays the CSS attributes and values for any modified settings.

Figure 6-6 The HTML-produced input form fields


Chapter 6:

Modifying Your Applicationâ&#x20AC;&#x2122;s Appearance

Figure 6-7 The Flex application with two different button text styles

Figure 6-8 The Flex Style Explorer displaying the application-level styles

153


154

Flex 3: A Beginner’s Guide

External CSS Flex, in an effort to make development easier, borrows the CSS concept from HTML in its entirety. This provides for an easy way to keep a related group of style definitions all in one file that can be referenced from the Flex application. Referencing a CSS file from a Flex application is called referencing an external CSS. Remember that when including themes available on the Internet, one of the ways to activate them in the application is to reference an external CSS file using the <mx:Script> tag and the style property. Of course the file must contain the style Type or Class definitions that you’ll use in the application. <mx:Style source="path/style.css"/>

This includes all of the styles in the stylesheet called style.css in the path directory. You cannot include an SWC file; however, your stylesheet can reference an SWC file if necessary when developing a theme.

Skins Skins are a technique for mapping an image onto a control. You may recognize skins from other popular open-source applications like WinAmp that have extension skin libraries to modify the application’s appearance with a set of images. Flex allows mapping skins to controls using images of your choice. Skins may be defined either using graphic images, called graphical skinning, or by defining the skin using code, called programmatic skinning. Of the two, graphical skinning tends to be quicker and easier to implement and will be the focus of this book.

Graphical Skinning Graphical skinning can be accomplished using the CSS techniques discussed previously along with a special set of properties for components that relate to skinning. Although you’re free to skin just about anything in Flex, it usually makes sense to start with basics such as buttons, check boxes, and progress sliders. The source image for your skin can be any Flex-supported image type, including GIFs, JPEGs, and PNGs. The images should be selected or created so that they look good when displayed together on the components of your application. You can use different skins to reflect the different states of a component. Some common states related to interaction with the user make sense to skin, such as mouse over, mouse down, and mouse off states. The skins should reflect the state, for example, a darker skin for when the mouse is over rather than when the mouse is not. This is similar to using JavaScript to perform an image


Chapter 6:

Modifying Your Application’s Appearance

rollover change in HTML. Again, there are many similarities between HTML and Flex development. Using the Flex Developer Guide, you can look up the skin properties for any component, but here’s a hint: they tend to be similar, so although the properties listed in Table 6-2 are for a CheckBox control, they are likely to work for many components, whether for a Button or a CheckBox or a textArea. To look up the styles for a check box, use the keywords mx.controls CheckBox in the Developer Guide navigator of your version of Flex from http://livedocs.adobe.com/flex.

NOTE The styles related to skins all have the word Skin in them.

You can either search the web for images that you like or create your own using image editing software such as Illustrator or Photoshop. Flex supports transparent image types for backgrounds, including GIF, PNG, and SWF files. In this example, we’ll create three basic images to represent the mouse down, over, and up states for a check box. Note that in this example once the check box is selected, it reverts back to the standard skins, since only the skin properties for the non-selected state were set. Likewise, if the CheckBox is disabled, then the default skins are used. The following examples use three images called checkbox_up.png, checkbox_over.png, and checkbox_down.png. They’re shown in respective order in Figure 6-9. Style

Purpose

disabledSkin

Skin that displays when the control is disabled

downSkin

Skin that displays when the mouse is down

overSkin

Skin that displays when the mouse is over

upSkin

Skin that displays when the mouse is not over the control

selectedDisabledSkin

Skin that displays when the control is selected but disabled

selectedDownSkin

Skin that displays when the control is selected and the mouse is down

selectedUpSkin

Skin that displays when the control is selected and the mouse is up

selectedOverSkin

Skin that displays when the control is selected and the mouse is over

Table 6-2 Common Skin-Related Styles

155


156

Flex 3: A Beginner’s Guide

Figure 6-9 The images to skin the CheckBox

Let’s test the skins using inline style definitions that are part of the <mx:CheckBox> tag. Listing 6-3 Skins Using Inline Styles <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Button label="Custom CheckBox" overSkin="@Embed('checkbox_over.png')" downSkin="@Embed('checkbox_down.png')" upSkin="@Embed('checkbox_up.png')"/> </mx:Application>

When compiled and run, as long as you have the images in the same directory as the application, the output looks similar to Figure 6-10. The @Embed keyword tells Flex to add the image into the SWF file when you compile your project. Generally, it’s best not to specify the filename of the image within the MXML tag for the component. A style can define the image’s filename instead. The next example combines two concepts into one example. It no longer uses the inline style definition to map the images. Also, it pulls the image filename out of the

Figure 6-10 The Custom CheckBox when the CheckBox is in the up state


Chapter 6:

Modifying Your Application’s Appearance

Figure 6-11 The Custom CheckBox in the mouse over state

MXML CheckBox tag that creates the CheckBox and places it into the CSS. The new CSS file is called checkbox_skin.css and contains the same style definitions: .customCheckBox { overSkin: Embed(source="checkbox_over.png"); downSkin: Embed(source="checkbox_down.png"); upSkin: Embed(source="checkbox_up.png"); }

The application’s MXML becomes the following code: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Style source="checkbox_skin.css" /> <mx:CheckBox label="Custom CheckBox" styleName="customCheckBox" /> </mx:Application> Makes the style information in the CSS available to this application.

The application appears the same as the inline example. Figure 6-11 shows the CheckBox while the mouse is over it. These examples all assume that the images and the CSS are placed in the project’s root directory. Otherwise, a path relative to the root needs to be included for Flex to find them when compiling the application. When creating the images to skin your components, you’ll need to tweak the size of the image to match the size of the component, since Flex automatically scales the image to match the size of the component. The result is a distorted image if your source image is of a different shape than the component. We’re going to introduce security in the next chapter and some pertinent details you should take into consideration, since there are malicious users out on the Internet.

157


This page intentionally left blank


Chapter

7

Data Access

159


160

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

Local Versus Remote Data

Security Implications

XML HTTP Service Requests

L

ocal data is data entered when coding the application or data that a user entered into a control and is remembered by the application. The ability to work with remote data that comes from a source outside of the application opens up the possibility of displaying a whole range of useful information through the application to the user. Traditional dynamic server-side web applications access data through an interface with a database. The applications are coded in languages such as PHP, ColdFusion, ASP, or Java. They communicate with the database on the web server. A cross-domain file mitigates the security risk of a malicious Flex or Flash application retrieving data that’s behind a user’s firewall. The cross-domain file must be located on a web server within the same domain name to allow Flex clients to access resources on that server. Those resources include SWF files, images, and XML feeds. As an alternative to using a cross-domain file, a proxy can be used to ensure the security of the Flex application by funneling the data access to a point that is outside of the end user’s network. One of the tools that Flex provides to access remote data is called the XML HTTP Service Request. It’s a form of a Remote Procedure Call (RPC) request. The component combines functionality of requesting XML data from a server and decoding the XML data. Since Really Simple Syndication (RSS) feeds are already in XML format, they make for a great simple example of embedding dynamic remote data into a Flex application. The Flex application will use an HTTP Service Request to get the XML data through the proxy. Then it displays some of the fields that are available in the XML feed. Several components are used to display the data, including DataGrid, Label, LinkButton, and TextArea. The DataGrid control lists objects linked within the rssRequest object. Because there are multiple items in the RSS feed, it will automatically repeat in the DataGrid for each list item. Since the RSS XML includes a description attribute with HTML content, a TextArea can be used to display the HTML of the currently selected item from the DataGrid.


Chapter 7:

Data Access

Local Versus Remote Data So far all of the data we’ve worked with in Flex has been locally defined data. Local data is data entered when coding the application or data that a user entered into a control and is remembered by the application. The ability to work with remote data that comes from a source outside of the application opens up the possibility of displaying a whole range of useful information through the application to the user.

Security Implications Traditional dynamic server-side web applications access data through an interface with a database. The applications are coded in languages such as PHP, ColdFusion, ASP, or Java. They communicate with the database on the web server. Since all of this happens on the web server, that’s where you manage security. Flex, on the other hand, executes the application on the user’s computer via the Flash plug-in. Allowing the flash plug-in to access resources on the local network of the user could bypass that user’s firewall and generally open a window for malicious Flex applications that could pilfer data. Figure 7-1 illustrates how improper security in the Flash plug-in could compromise a user’s network.

Figure 7-1 The potential security risk of applications running in the browser

161


162

Flex 3: A Beginner’s Guide

In order to keep user’s data safe, the Flash player returns only information from the server that exactly matches the domain name from which the Flex application was retrieved. Any attempt to access a data source in a different domain is ignored by the Flash player. Flex does provide a couple of mechanisms for accessing data from other sources that don’t compromise an end user’s security.

Cross-Domain File A cross-domain file mitigates the security risk of a malicious Flex or Flash application retrieving data that’s behind a user’s firewall. The cross-domain file must be located on a web server within the same domain name to allow Flex clients to access resources on that server. Those resources include SWF files, images, and XML feeds. This policy file is called crossdomain.xml. To give the web site examplesite.com access to data on anotherdomain.com, do the following: 1. Using a text editor of your choice such as Notepad or TextEdit, create a file called

crossdomain.xml. 2. To define the text’s XML type, add the following to the XML file: <?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">

3. To begin defining the access policies, add a cross-domain policy block to the end

of the file:

The <allow-access-from> tag defines which

domains may access the resources. <cross-domain-policy> <allow-access-from domain="examplesite.com" /> </cross-domain-policy>

More than one <allow-access-from> line can be listed to allow multiple domains to access the resource. Wildcards can also be used to allow access from a wider range of domains. 4. Save the file. It should now look like this: <?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <allow-access-from domain="examplesite.com" /> </cross-domain-policy>


Chapter 7:

Data Access

5. Place the crossdomain.xml file into the root shared directory of the web server that’s

providing the resource, in this example anotherdomain.com. If the web server is on a different computer, use a file transfer program such as FTP. The location of the root shared folder varies by web server type. For Apache 2.2, it’s usually a directory like C:\Program Files\Apache Software Foundation\Apache2.2\htdocs, or for IIS, C:\Inetpub\wwwroot. For Mac OS X users, this directory is often located within your account home directory as Sites. Verify that the file is accessible by navigating to http://anotherdomain.com/ crossdomain.xml.

Proxy As an alternative to using a cross-domain file, a proxy can be used to ensure the security of the Flex application by funneling the data access to a point that is outside of the end user’s network. Typically the proxy is located on the same server that the Flex application is hosted on. A full-featured proxy system is included with LiveCycle Data Services, but don’t worry if LiveCycle Data Services is beyond your price range. Simple Flex proxies are available for free using server-side technologies like PHP, ASP, ColdFusion, and Java. The proxy service works by passing along requests from the Flex application to the source of the data and returning the data to the Flex application.

TIP Go to http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_16520&sliceId=2 for more information and a listing of free Proxy code for a variety of server types.

The proxy can be hosted on the same computer that’s being used when writing the application and testing it. A local web server that supports a server-side scripting technology must be present.

Using a Proxy in Flex Builder In order to use a proxy, Flex must know how to reach it. The proxy must be located in the same domain that’s hosting the SWF file. You’ll need to specify the location of the proxy before building and deploying the SWF and HTML wrapper files.

163


164

Flex 3: A Beginner’s Guide

To modify the Run Configuration in Flex Builder: 1. Select Profile from the Run menu. 2. Select the application to be modified. 3. If Use Defaults is selected, deselect it. 4. Enter the URL where the application will run, for example, http://example.com/test/

TestProxy.html. 5. Enter a debugging URL in the debug URL field if one exists. 6. Click Apply to accept the changes and close the dialog.

If the proxy server is on the local computer, Flex Builder needs to know the final destination where the application is built and served: 1. Select the properties by right-clicking (on the Mac CONTROL-click) the project in the

Navigator view and selecting Properties. 2. Select the Flex Build Path entry. 3. Set the output directory by clicking the Browse button next to the output directory. 4. Select the directory that’s serving the application locally. This directory is under the

web root folder on your computer, which varies, depending on your OS and web server configuration. 5. Click OK to accept the changes.

The proxy server-side files must be copied to a directory under the web root regardless of whether the localhost is the web server or a remote host is the web server. We’re going to address using HTTP Service Requests next.

XML HTTP Service Requests One of the tools that Flex provides to access remote data is called the XML HTTP Service Request. It’s a form of a Remote Procedure Call (RPC) request. The component combines


Chapter 7:

Data Access

functionality of requesting XML data from a server and decoding the XML data. As we have mentioned, in order for Flex/Flash Player to access data on a remote server (other than the server the application is hosted on), it must have a crossdomain.xml policy that allows access for the domain from which the Flex Application is hosted. Other types of RPC calls include web services and remote objects for Java. Since Flex doesnâ&#x20AC;&#x2122;t directly interact with a database, another method of data retrieval is necessary. A web server can be set up to respond to an HTTP Service Request by querying a database and returning the results in XML format. Figure 7-2 shows how HTTP Service Requests fit into the processing of Flex applications.

NOTE An HTTP Service Request can parse data other than XML data. The HTTPService.resultFormat property can be set to values such as flashvars to parse data in name-value pairs or text to leave the results as raw text.

Figure 7-2 Processing an HTTP Service request in a Flex application

165


166

Flex 3: A Beginner’s Guide

Try This

Creating an Application to Display Amazon Vampire Books

Since Really Simple Syndication (RSS) feeds are already in XML format, they make for a great simple example of embedding dynamic remote data into a Flex application. In this project a proxy at http://www.krautboy.com/flex_proxy.php reads the Amazon feed for products tagged with Vampire.

Proxy Ideally, Amazon.com would allow access in their crossdomain.xml file, but they don’t, so the proxy must be used. The code for the proxy is very straightforward: <?php $rssFeed = "http://www.amazon.com/rss/tag/vampire/recent/ref=tag_rsh_hl_ersr"; //must be the source RRS page and not a redirect readfile($rssFeed); ?>

The Flex application will use an HTTP Service Request to get the XML data through the proxy. Then it displays some of the fields that are available in the XML feed. Several components are used to display the data, including DataGrid, Label, LinkButton, and TextArea. Because of security ramifications, applications running in Flash Player on a client computer can only access remote data sources if one of the following conditions is met: ●

A compiled SWF file is in the same domain as the remote data source.

A proxy is used and your SWF file is on the same server as the proxy.

Additionally, Adobe Flex Data Services provides a complete proxy management system for Flex applications. But, you can create a simple proxy service using a web scripting language such as ColdFusion, JSP, PHP, or ASP.


Chapter 7:

Data Access

Adding Controls for Data Display In order to display the data for the source, several controls are added to the screen. 1. Launch Flex Builder and open a project. 2. Create a new MXML application called BookBrowser.xml by selecting MXML

Application from the File | New menu. 3. Set this file as the default file to be compiled by selecting Set As Default Application

from the drop-down context menu. The context menu appears when right-clicking (CONTROL-click on the Mac) on the file in the Navigator view. If there are other application files in the project, this application will be executed by default. 4. In Design mode drag a Panel container from the Components view to the upper

left-hand corner of the Design window. 5. In the properties pane for the panel set the width to 500, the height to 500, and the title

to Vampire Books. The exact X and Y placement of the panel doesn’t matter, but the example code illustrates a placement of 0,0. 6. Drag a VBox layout container from the Component view into the panel container’s

upper left-hand corner. Accept 100% as the height of the VBox when prompted. Also set the Width property to 100%. 7. Add the following in order to the VBox from the Component controls listing: ●

DataGrid

TextArea

LinkButton

8. The component should display in a vertical column within the VBox. 9. Select the DataGrid control and set its Id property to datagridBooks, its width to

100%, and its height to 200. 10. Select the LinkButton control and set the Label property to Goto Book. 11. See Figure 7-3 for how the Design Mode window should appear.

(continued)

167


168

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 7-3 The Design window with the Panel, VBox, and Display controls 12. Switch to the Source view. At this point the MXML code should be similar to Listing

7-1 (x and y positions may vary). Listing 7-1 Data Grid Column Layouts <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Panel width="500" height="500" layout="absolute" title="Vampire Books"> <mx:VBox width="100%" height="100%">


Chapter 7:

Data Access

<mx:DataGrid width="100%" height="200" id="datagridBooks"> <mx:columns> <mx:DataGridColumn headerText="Column 1" dataField="col1"/> <mx:DataGridColumn headerText="Column 2" dataField="col2"/> <mx:DataGridColumn headerText="Column 3" dataField="col3"/> </mx:columns> </mx:DataGrid> <mx:TextArea width="100%" height="200"/> <mx:LinkButton label="Goto Book"/> </mx:VBox> </mx:Panel> </mx:Application>

13. Save the file by selecting Save from the File menu. 14. Select Run BookBrowser from the Run menu. 15. After a brief pause for compiling, the application appears in your default browser like

Figure 7-4.

Figure 7-4 The basic layout of the application before loading data

(continued)

169


170

Flex 3: A Beginner’s Guide

At this point the framework for displaying the book information is present, but there is no data to display.

Getting the Data The HTTPService RPC request supplies the data. Remember that the actual request comes from the proxy set up at http://www.krautboy.com/flex_proxy.php. The proxy in turn requests the XML data from http://www.amazon.com/rss/tag/vampire/recent/ref=tag_ rsh_hl_ersr. When HTTPService is called, Flex makes a HTTP GET or POST request to the remote server. The remote server returns the XML data. The <mx:HttpService> tag has a property called url that specifies the HTTP URL of the resource that supplies the data. In this example it’s http://www.krautboy.com/flex_ proxy.php, which simply passes along the request to Amazon.com’s RSS feed. The krautboy.com domain has a crossdomain.xml file set up to allow access to this resource from any browser’s Flash plug-in. To add this request, follow these steps: 1. Working with the BookBrowser.mxml file from Listing 7-1, enter Source mode. 2. After the <mx:Application> tag, enter a <mx:HTTPService> tag like this:

<mx:HTTPService id="rssRequest" url="http://www.krautboy.com/flex_proxy.php" /> 3. To tell the application that it must load the data from the HTTPService tag when the

application loads, add a createComplete policy to the <mx:Application> tag. The text in bold must be added; it specifies that the send method should be called for the request: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="rssRequest.send()">

Now that the data source is set up and the code to request the data at startup is in place, it’s time to test to see if there is some data coming from the feed. To test the application, bind a field from the XML source to a component. In this example, the title of the RSS feed is bound to the Panel’s title property: 4. Replace the static title with text provided from the root level of the XML feed for the

title by adding a binding expression to the Panel tag: title="{rssRequest.lastResult.rss.channel.title}"


Chapter 7:

Data Access

The code should now look like Listing 7-2. Listing 7-2 RSS Feed <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="rssRequest.send()" layout="absolute"> <mx:HTTPService id="rssRequest" url="http://www.krautboy.com/flex_proxy.php" /> <mx:Panel width="500" height="500" layout="absolute" title="{rssRequest.lastResult.rss.channel.title}"> <mx:VBox width="100%" height="100%"> <mx:DataGrid width="100%" height="200" id="datagridBooks"> <mx:columns> <mx:DataGridColumn headerText="Column 1" dataField="col1"/> <mx:DataGridColumn headerText="Column 2" dataField="col2"/> <mx:DataGridColumn headerText="Column 3" dataField="col3"/> </mx:columns> </mx:DataGrid> <mx:TextArea width="100%" height="200"/> <mx:LinkButton label="Goto Book"/> </mx:VBox> </mx:Panel> </mx:Application>

Since Flex automatically translates the XML into object form, it can be referenced using dot notation to drill down like rss.channel.title, which directly translates to the XML layout of Listing 7-3. Listing 7-3 Recently Tagged Products <?xml version="1.0"?> The attribute thatâ&#x20AC;&#x2122;s referenced as rss.channel.title. <rss version="2.0"> <channel> <title>vampire: Recently tagged products at Amazon.com</title> <link>http://www.amazon.com/tag/vampire/products/ref=tag_rsr_rs_istp_chanlink</link> <description><![CDATA[Products on amazon.com which have recently been tagged "vampire".]]></description> Other XML attributes have been removed from this file, </channel> including the book items. </rss>

The rssRequest.lastResult portion indicates that the HTTPService component with the id of rssRequest translated the object and named it lastResult.

(continued)

171


172

Flex 3: A Beginner’s Guide

NOTE If you navigate to http://www.amazon.com/rss/tag/vampire/recent/ in your browser and choose to View Source, then you can see the RSS XML source in its entirety. Listing 7-3 has been edited for readability. The complete source has several other channel attributes as well as an item entry for each result.

At this point it’s a good idea to see if the last change works okay. 1. Save the file. 2. Select Run BookBrowser from the Run menu. 3. After compiling, the application launches in your browser. 4. At first, the data won’t display, as Flex is fetching the XML and parsing it. After the

initial pause, the application looks like Figure 7-5, with the title text coming from the RSS feed.

Figure 7-5 The BookBrowser application with the dynamic title


Chapter 7:

Data Access

Linking the DataGrid to the Data The DataGrid control will list the most recent books tagged as Vampire. In order to do so, it must be linked with the rssRequest object you created above. Because it will be linked at the item level and there are multiple items in the RSS feed, it will automatically repeat in the DataGrid. Additionally, each field to be displayed, such as the title, data, and ASIN/Tag, must be linked to a column. To link the columns, modify the column’s dataField attribute to be the name of the XML field. The following steps add the dataProvider and dataFields: 1. Continuing with the file from the last set of steps, in source mode bind the RSS object

at the item level by adding the bolded text to the <mx:DataGrid> tag: <mx:DataGrid width=“100%” height=“100%” id=“datagridBooks” dataProvider=“{rssRequest.lastResult.rss.channel.item}”> 2. Use the dataField property to associate the title attribute from the data provider. For the

first <mxDataGridColumn> set headerText to Title and dataField to title: <mx:DataGridColumn headerText=“Title” dataField=“title”/> 3. For the second <mxDataGridColumn> set headerText to Published and dataField to

pubDate: <mx:DataGridColumn headerText=“Published” dataField=“pubDate”/> 4. For the third <mxDataGridColumn> set headerText to ASIN/Tag and dataField to guid:

<mx:DataGridColumn headerText=“ASIN/Tag” dataField=“guid”/> 5. The source of the application should now look like Listing 7-4.

Listing 7-4 DataGrid Control <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="rssRequest.send()" layout="absolute"> <mx:HTTPService id="rssRequest" url="http://www.krautboy.com/flex_proxy.php" /> <mx:Panel width="500" height="500" layout="absolute" title="{rssRequest.lastResult.rss.channel.title}"> <mx:VBox width="100%" height="100%"> <mx:DataGrid width="100%" height="200" id="datagridBooks" dataProvider="{rssRequest.lastResult.rss.channel.item}"> <mx:columns>

(continued)

173


174

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

<mx:DataGridColumn headerText="Title" dataField="title"/> <mx:DataGridColumn headerText="Published" dataField="pubDate"/> <mx:DataGridColumn headerText="ASIN/Tag" dataField="guid"/> </mx:columns> </mx:DataGrid> <mx:TextArea width="100%" height="200"/> <mx:LinkButton label="Goto Book"/> </mx:VBox> </mx:Panel> </mx:Application>

When the application is run at this point, it should display data from the RSS XML in the DataGrid Control, as shown in Figure 7-6. The next step is to bind the TextArea to the DataGrid and Data Provider.

Figure 7-6 The application populates the DataGrid control.


Chapter 7:

Data Access

Linking the TextArea to the Data Since the RSS XML includes a description attribute with HTML content, a TextArea can be used to display the HTML of the currently selected item from the DataGrid. To link the TextArea in the example code to the DataGrid, modify the htmlText property to reference the datagridBooks object. The currently selected item is referenced as selectedItem. Any fields within the item can be referenced via selectedItem, and therefore, the description is available as selectedItem.description. To make the changes: 1. In source mode, modify the <mx:TextArea> tag to bind the selected description by

adding the code in bold: <mx:TextArea width="100%" height="200" htmlText="{datagridBooks.selectedItem.description}" /> 2. Save the file. 3. Select Run BookBrowser from the Run menu. 4. After compiling, the application launches in your browser. 5. Select an entry from the dataGrid. Figure 7-7 shows a book’s description in the

TextArea.

NOTE This application is working with a live data feed; therefore, the items shown when running the application will not be the same as Figure 7-7.

Linking the Button to the Data In addition to providing a title and a description, most RSS feeds also provide a link to the URL of the original book or article. In this case, the Button links to the URL of the currently selected book. When the user clicks the Goto Book button, the book’s full page displays in the user’s browser. Because the link from the RSS feed is just a string, a couple of helper functions are required. First, the URLRequest function converts the link string into a URLRequest object. It references the link from the current selection using the same drill-down style as the TextArea. Finally, the navigateToURL function uses the URLRequest object to open the link in a new browser window.

(continued)

175


176

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 7-7 A book displays in the TextArea.

To create the LinkButtonâ&#x20AC;&#x2122;s binding to the selected item: 1. In source mode, modify the <mx:LinkButton> tag to include a click property set to the

current link field. To bind the selected description, add the code in bold: <mx:LinkButton label="Goto Book" click="navigateToURL(new URLRequest(datagridBooks.selectedItem.link));"/>


Chapter 7:

Data Access

2. The code should look like Listing 7-5.

Listing 7-5 Linking the Button to the Data <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="rssRequest.send()" layout="absolute"> <mx:HTTPService id="rssRequest" url="http://www.krautboy.com/flex_proxy.php" /> <mx:Panel width="500" height="500" layout="absolute" title="{rssRequest.lastResult.rss.channel.title}"> <mx:VBox width="100%" height="100%"> <mx:DataGrid width="100%" height="200" id="datagridBooks" dataProvider="{rssRequest.lastResult.rss.channel.item}"> <mx:columns> <mx:DataGridColumn headerText="Title" dataField="title"/> <mx:DataGridColumn headerText="Published" dataField="pubDate"/> <mx:DataGridColumn headerText="ASIN/Tag" dataField="guid"/> </mx:columns> </mx:DataGrid> <mx:TextArea width="100%" height="200" htmlText="{datagridBooks.selectedItem.description}"/> <mx:LinkButton label="Goto Book" click="navigateToURL(new URLRequest(datagridBooks.selectedItem.link));"/> </mx:VBox> </mx:Panel> </mx:Application>

3. Save the file. 4. Select Run BookBrowser from the Run menu. 5. After compiling, the application launches in your browser. 6. Select a book from the dataGrid. 7. Click the GoTo Book button. 8. The bookâ&#x20AC;&#x2122;s page displays in your browser similar to Figure 7-8.

(continued)

177


178

Flex 3: A Beginner’s Guide

Figure 7-8 The book displays in the browser.

Debugging is very important. Since you’ve now created a lot of workable code, it’s important to learn all about debugging your code, because mistakes happen and you want to make sure you have the most accurate, error-free code.


Chapter

8

Debugging and Profiling

179


180

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

Profiling

Live Objects Panel

Memory Snapshot Panel

Loitering Objects Panel

Object References Panel

Allocation Trace Panel

Performance Snapshot Panel

Debugging with fdb

Commands

Debugging

Y

our major concern when developing Flex applications is that they operate correctly, and profiling and debugging are invaluable tools for assuring that they do. You can use profiling by putting the debug output into your application and checking the output log to view any debug statements. The profiler tracks several categories of performance metrics. As memory usage is profiled, you may notice that it tends to go up and down without any precise pattern. This happens because of the way the Flash Player/Flex manages memory. Memory management is automatically taken care of by the garbage collector. The garbage collector frees up memory from processes that aren’t being used so that it can allocate it to other operations. The Live Objects panel shows class and package names of objects that were added since the application started to run. The panel also displays memory usage and the number of times the class has been instantiated. As garbage collection runs, the current memory use may go down but the cumulative values will also increase. The Memory Snapshot panel captures memory usage for all classes from the point of the capture. Whatever memory was being utilized during the snapshot capture is displayed for your information in the Memory Snapshot panel of Flex Builder. You need multiple snapshots to compare them to real-time usage of your application.


Chapter 8:

Debugging and Profiling

Loitering objects are objects that remain in memory longer than they should. A piece of memory that is allocated and freed repeatedly but doesn’t release all of the memory can cause a memory leak. You can access this through the Loitering Objects panel. This information can then be used to figure out which class used up more memory than it should have. The Object References panel displays after a class was selected from the Loitering Objects pane. It traverses the heap, a special portion of memory that tracks the execution of code, to see what objects referenced the object in question. It’s one of these references that is keeping the object from being freed by garbage collection. The Allocation Trace panel shows memory usage by function. This makes it easy to find which functions are using the most memory if you are trying to reduce overall memory consumption. The Performance Snapshot panel displays information from the Performance Snapshot, which works similar to a memory snapshot but records duration of execution time and frequency instead of memory statistics. The Flex command-line debugger is called fdb. If you’ve ever used a command-line debugging tool before, it should seem familiar. It provides similar functionality to the Flex Builder debugger such as breakpoints but doesn’t require Flex Builder to run. It’s distributed with the Flex SDK and is located in the binary directory. There are various commands that fdb uses to modify the behavior of the debugger. Some of them are: break, disable, enable, handle, next, and print. Another debugging option is the trace() function. It is a convenient tool for both determining where a program is in its execution and writing out debugging values without having to set specific breakpoints and display statements. The trace statement can go anywhere in your ActionScript code and will write out the value that the function takes as an argument. The Code Editor is used to locate and highlight lines of code in order for you to fix the errors. For example, you can set breakpoints to stop script execution in order to inspect the variable values or other information up to that point in your code. A breakpoint basically establishes a place for your Flex application to pause. By pausing the application, you can then view a snapshot of the application’s current state. Lastly, the Flex Debugger perspective offers the following views: debug, breakpoints, console, variables, and expressions.

Profiling When developing a Flex application, the first thing to worry about is producing an application that functions correctly, but once that stage has been reached, it may be

181


182

Flex 3: A Beginner’s Guide

necessary to make the application run faster. In its most simplistic sense profiling can be accomplished by placing debug output into an application and checking an output log to see when the debug statements are encountered, but this method isn’t very robust or easy to use. To aid developers in determining which portions of their code are consuming the most time, Flex includes a perspective called the Profiling perspective. Flex Builder works with the Debugging Flash plug-in that was installed when Flex Builder was installed, since the regular Flash plug-in does not collect the required debugging and profiling information. The profiler is a major new enhancement in Flex Builder 3. Prior versions of Flex Builder required cobbling together several utilities to produce the results that are now integrated in the Flex Builder perspective. The profiler tracks several categories of performance metrics, including memory usage, execution time, and frequency of execution. These values are separated out by the class methods that are called, including the Flex Framework classes.

NOTE The Flex 3 profiler can be used to profile older Flex 2.x applications and Flash AS3 (but not AS2) applications. Adobe AIR (stand-alone) applications can also be profiled.

As memory usage is profiled, you may notice that memory usage tends to go up and down without any precise pattern. This happens because of the way the Flash player and Flex manage memory. In Flex Builder memory management is handled automatically in a process called garbage collection. The Flash player allocates memory in large chucks from the operating system and then doles out bits to the application as it runs. Every so often, as new memory is requested, the garbage collection process looks at objects that are no longer being used, for example, if they’ve been set to null. It will free up memory for as many of those objects as it finds, but there is some randomness to the process that makes it impossible to know exactly how much memory is freed each time. Although any Flex application that’s compiled with debugging information can be profiled, the following example demonstrates how the profiler works. Follow these steps to begin profiling the example code, which takes a number in a TextArea and calculates its factorial when the Calculate button is pressed:


Chapter 8:

Debugging and Profiling

1. Create a new MXML application called factorial.mxml in a project. 2. Select the Source view and paste in this code: <?xml version="1.0" encoding="UTF-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script> <![CDATA[ private function calculateFactorial(n:String):String { This function does the mathematical var y:Number=1; calculation and returns the number for (var x:Number = 1;x <= Number(n); x++) { as a string. y = y * x; } return String(y); } ]]> </mx:Script> Call the calculate function when the button is <mx:Panel title="Calculate Factorial"> clicked and send the number as a parameter. <mx:HBox> <mx:Label text="Input:"/> <mx:TextInput id="textArea1" text="1"/> <mx:Button id="button1" label="Calculate" click="result.text = calculateFactorial(textArea1.text)"/> </mx:HBox> <mx:HBox> <mx:Label text="Factorial:"/> <mx:Label id="result"/> </mx:HBox> </mx:Panel> </mx:Application>

3. Run the application in the profiler by either selecting Profile Factorial from the Run

menu or clicking the Profiler button as shown in Figure 8-1. Figure 8-1 also shows the code in Source mode before clicking the Profiler button.

NOTE If your browser is using Tabbed browsing (multiple web pages under separate tabs), you may receive a warning from Flex that profiling may not start properly. If it doesnâ&#x20AC;&#x2122;t work, close your open tabs and try again.

183


184

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Launch in Profiler

The source code of the application to profile

Figure 8-1 The code in Source view and the Profiler button in Flex Builder

4. Flex opens the application in the default browser and pauses execution just after the

application loads. A Connection Established dialog appears as shown in Figure 8-2. 5. Click the Resume button to accept the defaults. The options have the following

meaning: â&#x2014;?

To monitor how much memory is used and freed as objects are created and removed by garbage collection. Leave the Enable Memory Profiling option selected.


Chapter 8:

Debugging and Profiling

Figure 8-2 The Connection Established dialog with default options selected

To see live updates on memory usage via the Live Objects panel. Leave the Watch Live Memory Data check box selected.

The Generate Object Allocation Stack Traces option is not selected by default, since it can slow down the execution of the application, as the Flash plug-in must keep stack traces each time an object is created.

The last option enables tracking how long methods take to execute.

6. Flex Builder displays the Profiling perspective as shown in Figure 8-3.

The Factorial application continues to run in the browser as shown in Figure 8-4.

185


186

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Live Objects panel

Figure 8-3 The Profiling perspective

Figure 8-4 The Flex application running in the browser


Chapter 8:

Debugging and Profiling

Saving and Loading Profiling Data Profile data can be loaded and saved from the Profile panel. The Profile panel is located at the top-right corner of the screen as shown in Figure 8-5. The profiling dialog also has a toolbar at the top, shown in Figure 8-5. The profiling buttons correspond to Resume, Suspend, Terminate, Run Garbage Collection, Take Memory Snapshop, Find Loitering Objects, View Allocation Trace, Capture Performance Details, Delete, and Profile Menu. To save a Profiling session, select Save from the Profiling drop-down menu. The profile is saved as a set of files that are used to load the profile back into Flex Builder. In order to load a saved file, follow these steps: 1. Select the Saved Profiling Data panel. 2. Click the Open Profile Folder button as shown in Figure 8-6. Profiling pane

Toolbar

Profile menu

Figure 8-5 The Profile dialog with toolbar

187


188

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Open Profile Folder button

Figure 8-6 The Saved Profile panel and the Open Profile Folder button

3. Select the directory that contains the saved profile and click OK. 4. The profile displays and can be selected in the Save Profile Data list.

Once the saved profile data has been loaded, the memory and performance snapshots can be viewed. Since the project is no longer running, new snapshots cannot be created.

Live Objects Panel The Live Object panel lists class and package names of any objects that have been created since the application started. Package names may be blank for some classes, especially if they are system classes. The panel also displays memory usage and the number of times the class has been instantiated. As garbage collection runs, the current memory use may go down but the cumulative values will also increase. Figure 8-7 shows the Factorial applicationâ&#x20AC;&#x2122;s memory usage, with the MethodClosure method being the most frequently instantiated method.


Chapter 8:

Debugging and Profiling

Figure 8-7 The Live Objects panel

Since the Live Objects panel tracks all classes, it could make debugging the code that’s central to the application being developed less clear. By default, Flex excludes classes beginning with mx or flash with the unnamed built-in package. If you’re curious how much memory and time the internal Flex and Flash classes consume, selecting the Filters button can modify these settings as shown in Figure 8-8. Any changes made to the filters will be saved until they’re changed again.

189


190

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Filters button

Figure 8-8 The Filters button

Memory Snapshot Panel A memory snapshot captures the memory usage for all classes at the point of time that the snapshot was taken. Snapshots can be viewed and compared against each other. To take a memory snapshot, click the Take Memory Snapshot button as shown in Figure 8-9. Once a memory snapshot has been taken, it can be displayed in the Memory Snapshot panel by double-clicking the snapshot. Figure 8-9 also illustrates a snapshot displayed in the Memory Snapshot panel. Multiple snapshots or a snapshot compared to real time enable comparison features that are discussed shortly, such as loitering objects and viewing the allocation trace.


Chapter 8:

Debugging and Profiling

Memory Snapshot button

Memory Snapshot panel

Figure 8-9 The Memory Snapshot button and panel

Loitering Objects Panel Loitering objects are objects that remain in memory longer than they should. A piece of memory that is allocated and freed repeatedly but doesnâ&#x20AC;&#x2122;t release all of the memory can cause a memory leak. The Loitering Objects feature can be used to help locate memory leaks that reduce the amount of free memory over time if not fixed. To use the Loitering Objects panel: 1. Take a snapshot of your application before any suspected memory leaks. 2. Perform the actions in the application that you suspect are causing a memory leak.

191


192

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

3. Take another memory snapshot of the application. 4. Select both the before and after snapshots in the Profile panel. Use the CTRL key to

select more than one snapshot. 5. Click the Find Loitering Objects button as shown in Figure 8-10.

The Loitering Objects panel displays as shown in Figure 8-10. Class, package, instance count, and memory usage are all displayed for objects that were created between snapshots. This information can then be used to figure out which class used up more

Find Loitering Objects button

Loitering Objects panel

Figure 8-10 A Find Loitering Objects comparison


Chapter 8:

Debugging and Profiling

memory than it should have. The class entries can be drilled down to reveal more information about the methods and properties that consumed the memory by displaying the Object References panel. Double-clicking the object brings up the Object References tab (panel).

Object References Panel The Object References panel displays after a class was selected from the Loitering Objects panel. It traverses the heap, a special portion of memory that tracks the execution of code, to see what objects referenced the object in question. Itâ&#x20AC;&#x2122;s one of these references that is keeping the object from being freed by garbage collection.

NOTE The Allocation Trace panel that displays next to the Object References panel will show information only if the Generate Object Allocation Stack Traces option was selected from the Connection Established dialog during the launch of the profiler.

Figure 8-11 shows that a mx.core:UIComponent:addedHandler is among the objects referencing the HaloFocusRect class.

Figure 8-11 The Object References panel after drilling down from HaloFocusRect

193


194

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Allocation Trace Panel The Allocation Trace panel shows memory usage by function. This makes it easy to find which functions are using the most memory if youâ&#x20AC;&#x2122;re trying to reduce overall memory consumption. Clicking two memory snapshots, as you might before selecting a Loitering Objects comparison, allows selecting the Allocation Trace button as shown in Figure 8-12. Clicking the button brings up the Allocation Trace panel itself, as shown in Figure 8-13. Remember that the Generate Object Allocation Stack Traces option must have been selected from the Connection Established dialog during the launch of the profiler to use the Allocation Trace.

NOTE The bracketed function names like [newclass], [mouseEvent], [textEvent], and [focusEvent] are virtual functions that Flex inserts into the allocation trace to represent processing time for non-ActionScript code such as the time the Flash Player spends processing user events.

Double-clicking an entry, for example, _factorial_mx_managers_SystemManager.create, shows detailed information about its memory usage as shown in Figure 8-14.

Allocation Trace button

Figure 8-12 The Saved Profile panel with two snapshots selected and the Allocation Trace button


Chapter 8:

Debugging and Profiling

Figure 8-13 The Allocation Trace panel

Figure 8-14 Detailed allocation data, including self and callee instances

195


196

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Performance Snapshot Panel A performance snapshot works similar to a memory snapshot but records duration of execution time and frequency instead of memory statistics. To take a performance snapshot, click the Performance Snapshot button shown in Figure 8-15 while profiling an application. A performance profile displays under the Performance Profile tab. The profile lists the number of calls, cumulative time, self time, average self time, and average cumulative time for each method as shown in Figure 8-16.

Performance Snapshot button

Figure 8-15 The Performance Snapshot button


Chapter 8:

Debugging and Profiling

Figure 8-16 The Performance Snapshot panel

To display more details per method, double-click an entry and the Performance Snapshot panel displays as in Figure 8-17.

Figure 8-17 Method Statistics for [execute-queued]

197


198

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Launch Dialog The Profile button shown in Figure 8-1 can also be used to profile applications that are external to the current project. To profile an external application: 1. Activate the drop-down list from the Profile button by clicking the arrow portion of the

button. You can also select the Profile submenu from the Run menu. 2. Select Other from the drop-down list. 3. The Profile window opens as shown in Figure 8-18. Click the Browse button to select

the directory where the external application is located.

Figure 8-18 The Launch dialog showing settings for the Factorial application


Chapter 8:

Debugging and Profiling

4. Select the Application file from the Application file drop-down list. 5. Click Profile to begin profiling the application.

Applications can also be profiled after starting them outside of Flex Builder using the feature Profile External Application. To profile an external application, utilize the following steps: 1. Select the Profile perspective by selecting Perspective | Flex Debugging from the

Window menu. 2. Select Profile External Application from the Profile menu. The Profile External

Application dialog appears as shown in Figure 8-19. 3. Select the appropriately named Launch The Application Manually Outside Flex

Builder radio button.

Figure 8-19 The Profile External Application dialog

199


200

Flex 3: A Beginner’s Guide

4. The default Connection Timeout of 15000 milliseconds means Flex Builder will wait

for 15 seconds to start a Flex application after clicking Launch. Click Launch to begin waiting for a connection. 5. Launch a Flex application on your local computer. For example, reloading a Flex

application in your browser causes the Profiler to attach it to that instance. 6. The Connection Established dialog appears and Profiling options can be set.

Another tool in the Flex toolbox for identifying problems in your MXML and ActionScript code is the command-line debugger.

Debugging with fdb The Flex command-line debugger is called fdb. If you’ve ever used a command-line debugging tool before, it should seem familiar. It provides similar functionality to the Flex Builder debugger such as breakpoints but does not require Flex Builder to run. It’s distributed with the Flex SDK and is located in the binary directory. On Windows, the full path is C:\Program Files\Adobe\Flex Builder 3 beta 2\sdks\3.0.0\bin\fdb.exe. You may find it helpful to add this directory to your system path so that you only need to enter fdb.exe to run the debugger.

NOTE Depending on your Flex installation and operating system, the path may be different than the path listed here. If necessary, searching for a filename beginning with fdb reveals the relevant path.

The stand-alone flash player version of the fdb debugger doesn’t open an instance of the application in the web browser and doesn’t support server requests, for example, working with external data sources. It’s possible to debug applications in the web browser plug-in using fdb by specifying a URL address instead of a plain SWF file location. To modify the system path on Windows: 1. Select Control Panel from the Start menu. 2. Open the System Control Panel (may be under Performance and Maintenance). 3. Select the Advanced tab. 4. Click the Environmental Variables button. 5. From the User variables for user list, select PATH and click Edit.


Chapter 8:

Debugging and Profiling

6. Add the path of fdb as installed locally plus a semicolon (;) to the beginning of the path

such as: C:\Program Files\Adobe\Flex Builder 3\sdks\3.0.0\bin;

7. Click OK to accept the change. 8. Click OK to accept the change. 9. Click OK to close the System Control Panel.

For Mac OS X and Linux, it’s beyond the scope of this book to modify the path; however, you can call fdb by using the full path.

NOTE If you haven't installed a standalone JRE, you'll also need to set the Environmental Variable $JAVA_HOME = c:/program files/adobe/flex builder 3/jre in the System Control Panel.

Launching To launch the fdb debugger: 1. Open a command-line prompt such as cmd for Windows, terminal for Mac OS X, or

xterm for Linux. 2. Change your current directory to the directory that contains the Flex Application file

to profile. 3. Compile your application into a SWF file using Flex Builder or mxmlc with the

debugging option set. For example, to compile the application factorial.mxml: mxmlc -debug=true factorial.mxml

4. Invoke the SWF file with fdb like the following: fdb factorial.swf

NOTE If invoking a LifeCycle Data Services application, specify the URL of the application such as http://localhost:8100/flex/DataApp.mxml. To have fdb automatically connect to a debugging SWF session started in the browser, don’t specify a filename or URL; instead, enter the run command after fdb starts.

5. The Flash Player Debugger launches as shown in Figure 8-20. 6. The Flash Player Debugger pauses the application’s execution and presents an (fdb)

prompt where commands can be entered.

201


202

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 8-20 The Flash Player Debugger waiting for input

In your code, breakpoints can be set. To continue execution of the application, enter the command continue and press ENTER at the (fdb) prompt. Once the application resumes execution, the stand-alone Flash Player displays the application as shown in Figure 8-21.

Figure 8-21 The Factorial application running in the stand-alone Flash Player


Chapter 8:

Debugging and Profiling

Commands At the (fdb) prompt, any of the commands in Table 8-1 can be entered to modify the behavior of the debugger. Command

Alias

Description

break <breakpoint>

b

Set a breakpoint.

bt

bt

Print back trace of application stack trace.

cf

cf

Display the line number and name of the current file.

clear <line/function>

cl

Clear a breakpoint for <line/function>.

condition <expression>

cond

Modify a conditional expression for a breakpoint.

continue

c

Continue running a paused application.

commands <commands>

com

Commands to execute when a breakpoint is hit.

delete <exp/bt>

d

Delete auto-display expressions or breakpoints.

directory <path>

dir

Add <path> to the source fileâ&#x20AC;&#x2122;s path.

disable <exp/bt>

disab

Disable auto-display expressions and breakpoints.

disassemble

disas

Disassemble functions or source lines.

display <expression>

disp

Add auto-display <expression>.

enable <exp/bt>

e

Enable auto-display expressions or breakpoints.

file <filename>

fil

Select an application to debug, but do not start its execution. A run command can be issued after this command to begin debugging the file.

finish

f

Continue until the current function ends.

handle <definition>

han

Define how to handle a fault using <definition>.

help

h

Display a summary of the commands available.

home

ho

info

i

kill

k

list

l

next <number>

n

Continue executing the next <number> lines of the program or until another stop point is hit such as the end of the program.

print <variable>

p

Print the value of variable <variable>.

Table 8-1 FDB Commands

Display details of the application being debugged.

203


204

Flex 3: A Beginner’s Guide

Command

Alias

Description

pwd

pw

Print the current working path.

quit

Exit the debugger.

run <file>

Run the file specified by <file>. Can be issued without a filename if a file command already specified a filename. If the file command wasn’t used and no file was specified, the debugger waits for a browser-based debug session to start.

set <expression>

se

Set a variable’s value using <expression>.

source <file>

so

Batch fdb commands from a file called <file>.

step <number>

s

Continue executing the next <number> steps of the program or until another stop point is hit such as the end of the program.

tutorial

t

A tutorial on fdb’s use.

undisplay <exp>

u

Remove auto-display expression <exp>.

viewswf <swf>

v

Limit the files displayed based on the <swf> swf.

what

wh

Display a variable’s context.

where

w

Print back trace of application stack trace.

Table 8-1 FDB Commands (continued)

After entering a command, you’re returned immediately to the command prompt unless the application is running and no stop points have been hit. If the prompt is not present, pressing ENTER can interrupt program execution. This example demonstrates some of the commands in Table 8-1 while debugging the factorial.mxml application: 1. Start with the running fdb session from that last example. 2. At the (fdb) prompt, enter continue to partially load the application. 3. Enter break calculateFactorial() to set a breakpoint at the calculateFactorial()

ActionScript function.


Chapter 8:

Debugging and Profiling

4. Enter display textArea1.text to display the value in the MXML variable textArea1.text

automatically at the breakpoint. 5. Enter display result.text to display the value in the MXML variable result.text

automatically at the breakpoint. 6. Enter continue to resume the application. The fdb window now looks like Figure 8-22. 7. Enter a value of 15 and press Calculate in the application. 8. Enter continue to resume the application. 9. Enter a value of 15 and press Calculate in the application. 10. The fdb window now looks like Figure 8-23.

Figure 8-22 The fdb window waiting for user input to hit the breakpoint in the application

205


206

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

The calculated value as captured from the componentâ&#x20AC;&#x2122;s text property The last value of textArea1, the user-entered value Encountered the breakpoint function

Figure 8-23 The fdb window after two rounds of execution

Debugging with Trace The trace() function is another convenient tool for both determining where a program is in its execution and writing out debugging values without having the set specific breakpoints and display statements. The trace statement can go anywhere in ActionScript code and writes out the value that the function takes as an argument. For example, the code for factorial.mxml can be modified to include two trace statements. 1. Modify the source MXML code as shown in bold:

Listing 8-1 factorial.mxml Code <?xml version="1.0" encoding="UTF-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script>


Chapter 8:

Debugging and Profiling

<![CDATA[ private function calculateFactorial(n:String):String { var y:Number=1; for (var x:Number = 1;x <= Number(n); x++) { y = y * x; trace('The value of x is:' + x); trace('The value of y is:' + y); } return String(y); } ]]> </mx:Script> <mx:Panel title="Calculate Factorial"> <mx:HBox> <mx:Label text="Input:"/> <mx:TextInput id="textArea1" text="1"/> <mx:Button id="button1" label="Calculate" click="result.text = calculateFactorial(textArea1.text)"/> </mx:HBox> <mx:HBox> <mx:Label text="Factorial:"/> <mx:Label id="result"/> </mx:HBox> </mx:Panel> </mx:Application>

2. Save and recompile the application. 3. Launch the code using the fdb debugger. 4. At the (fdb) prompt, enter continue to partially load the application. 5. At the (fdb) prompt, enter continue to finish loading the application. 6. Enter a value to calculate in the application and click the Calculate button.

The trace statements dump the labeled values of x and y text whenever the code is executed, as shown in Figure 8-24. Not only the frequency of the trace call but also the values for the variables are displayed.

207


208

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 8-24 The value of x and y are traced for a factorial of 15.

The trace output provides insight into what your program is doing while executing. Now that the profiler and command-line debugging have been covered, itâ&#x20AC;&#x2122;s time to discuss working with media assets and publishing options.


Chapter

9

Working with Media Assets/Deploying

209


210

Flex 3: A Beginner’s Guide

Key Skills & Concepts ●

Managing Media Assets

Embedding versus Runtime Referencing

Supported Media Types

Sound

Wrappers

Publishing Your Application

F

lash handles media types such as audio and video really well because it has an extensive library of functions for animating and displaying graphics as well as sounds. Flex embeds assets into your project, making them part of your compiled SWF file. But if you have too many assets that are large, this could create a long download time for your user. Runtime-referenced files are not part of the SWF file. The SWF file only includes a reference to the media assets relative to the SWF file. This has the advantage of reducing initial load times and making switching out assets easier, since a recompilation of the SWF isn’t required to change the asset. Similar to images, sounds can either be embedded or referenced at runtime. The Sound class is used to manage information about a sound. Although Flex doesn’t support every image and sound format, it supports enough formats so that images and sounds can be converted to a supported format without a lot of effort. By carefully selecting reasonably sized audio and graphical assets and reusing them when possible, the amount of data that must be downloaded for an application to run can be minimized. Regardless of whether you include media assets in the SWF file or as separate files, the files must be published to a web server to make them accessible to the users. Flex allows some control over how these files are bundled together. The HTML and JavaScript wrapper files that Flex generates helps to ensure that the end user can run the Flex application. It’s also important to know which files must be published as well as how to transfer the files to your web server.


Chapter 9:

Working with Media Assets/Deploying

Managing Media Assets One of Flash’s strong points is its handling of media types like sound and video. Because Flash has a very extensive library of functions for animating and display graphics as well as sounds, Flex inherits this power through the same ActionScript classes as Flash applications. Since the Flash player supports many popular image, sounds, and video formats, they can be natively used in Flex applications as well.

Embedding vs. Runtime Referencing One of the first decisions to make when using media assets in your Flex application is how to include them in the project. Flex has the ability to embed the assets, which essentially makes them part of the compiled SWF file. This has the advantage of assuring that the media asset is always available with the application, since they reside in the same file. The downside is that too many large assets embedded into an SWF file can make for a painfully long load time when the application starts. Runtime-referenced files are not part of the SWF file. The SWF file only includes a reference to the media assets relative to the SWF file. This has the advantage of reducing initial load times and making switching out assets easier, since a recompilation of the SWF isn’t required to change the asset. Additionally, sometimes the names of media assets and locations aren’t known at compile time; therefore, this is also a good case for runtime referencing of media assets. The one downside is the possibility that a referenced media asset won’t be present at runtime, causing a broken link.

NOTE Media assets can also be embedded by placing them into a Runtime Shared Library (RSL) that is also loaded when the SWF file loads. This has the advantage of being sharable between multiple SWF files, potentially reducing overall download time.

Determining to embed or runtime-reference your media assets can generally be boiled down to the weight of the trade-offs. For smaller assets embedding is usually the way to go—especially if the smaller assets are part of an application’s graphical skin, since loading the application before those assets would result in an application that doesn’t look right initially, and first impressions are important.

211


212

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Supported Media Types Flex natively supports the image types shown in Table 9-1. The quality of a bitmap image is affected by the combination of the resolution of the image and its color depth. Resolution determines how many individual pieces, called pixels, an image is broken up into. The more pixels, the more resolution and detail are available. Likewise, an image with more color depth can display more colors per pixel, which also creates more lifelike images.

Image Type

Lossless

Transparency Support Description

JPEG

No

No

The Joint Photo Experts Group image format is good for photographs. It reduces the image size substantially. The level of compression is selectable when saving JPEGs.

GIF

Yes

Yes

The Graphics Interchange Format (GIF) provides small file sizes at the cost of a limited color palette. GIF images are good for icons and skinning. Transparency is limited to transparent or not transparent per pixel. Although the GIF standard supports animation, Flash and Flex do not support this, as the native Flash animation is preferable.

PNG

Yes

Yes

The Portable Network Graphics (PNG) image type is a newer replacement for the GIF file type. PNGs support a wide range of colors but produce a larger image size than GIFs or JPEGs. They also support variable levels of transparency per pixel, called alpha transparency. Because PNG is a newer format, itâ&#x20AC;&#x2122;s not guaranteed to be 100 percent compatible with all web browsers, but all recent versions of the Flash plug-in support it.

Table 9-1 Comparison of Supported Image File Formats


Chapter 9:

Working with Media Assets/Deploying

Sound Similar to images, sounds can either be embedded or referenced at runtime. Sound has a few unique properties, such as volume level, and the number of channels, such as stereo versus mono. If you’ve ever tried to work with sound within a web application, you’ll appreciate that the Flash player and Flex provide a consistent, supported, full-featured API for sound playback. The Flash API for playing sounds allows for pausing and seeking as well as changing the volume and balance of sounds.

NOTE Flash and Flex only support playing files stored in the popular .mp3 file format. Other formats such as .wav files must be converted before being used in Flex.

Naturally, the same warning applies for embedding sounds as for graphics. Any large sound files will cause the SWF file to grow by the same size. When loading files at runtime, you can actually begin playing a file before it’s finished downloading. Several classes from the flash.media package, including Sound and SoundChannel, process sound support. The Sound class is used to manage information about a sound, while the SoundChannel class manages the playback of the sound. Each playing sound has its own associated SoundChannel object to control it.

Playing Embedded Sounds In order to play an embedded sound file: 1. Create a new ActionScript project in Flex Builder called AS_SoundEmbed. A plain

text file could also be used, but you need to be using the SDK. 2. Open the AS_SoundEmbed.as file in Flex Builder. 3. Paste the following code into AS_SoundEmbed: package { import flash.display.Sprite; import flash.media.Sound; import flash.media.SoundChannel; public class AS_SoundEmbed extends Sprite { [Embed(source="sound.mp3")] public var soundClass:Class;

213


214

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

public function AS_SoundEmbed() { var smallSound:Sound = new soundClass() as Sound; smallSound.play(); } } }

4. Import an mp3 file called sound.mp3 in the same directory as the project. The mp3 file

can be any valid mp3 file. Select Import | Other from the File menu. The Import dialog appears. 5. Expand the General category on the Import dialog. 6. Double-click the File System entry. Figure 9-1 shows the Import dialog before

double-clicking the File System Entry.

Figure 9-1 The Import dialog with the General category expanded


Chapter 9:

Working with Media Assets/Deploying

7. Click Browse to select the directory to import from. The Import From Directory dialog

appears. 8. Select the directory and click OK. The files in that directory display in a list on the File

System Import dialog. 9. Place a check mark next to the file to import, in this case, sound.mpg, and click Finish.

Figure 9-2 shows the Desktop files loaded in the File System Import dialog. 10. Flex Builder should now look similar to Figure 9-3. 11. Select Run AS_SoundEmbed from the Run menu. 12. The default browser launches and begins playing the mp3 file.

Figure 9-2 The File System Import dialog with sound.mp3 selected

215


216

Flex 3: A Beginner’s Guide

Figure 9-3 Flex Builder with an ActionScript embedded sound project file

Playing Referenced Sounds Playing referenced sounds isn’t that different than playing an embedded sound. There’s one new class called URLRequest that’s used to specify the location of the sound file. To play an embedded sound file: 1. Create a new ActionScript project in Flex Builder called AS_SoundReferenced. 2. Open the AS_SoundReferenced.as file in Flex Builder. 3. Paste the following code into AS_SoundReferenced:


Chapter 9:

Working with Media Assets/Deploying

package { import flash.display.Sprite; import flash.media.Sound; import flash.net.URLRequest; public class AS_SoundReferenced extends Sprite { public function AS_SoundReferenced() { var snd:Sound = new Sound(new URLRequest("sound.mp3")); snd.play(); } } }

4. Place an mp3 file called sound.mp3 in the same directory as the project. 5. Select Run AS_SoundReferenced from the Run menu. 6. The default browser launches and begins playing the mp3 file.

Including a Referenced Image To include a referenced image, use an <mx:Image> tag. The image tag works very similarly to the way an HTML <img> tag does, since they both define the display location, properties, and source path for displaying an image. For example, placing an image called compass.png into an MXML layout can be accomplished by adding the following line of code: <mx:Image x="10" y="10" id="compass" source="compass.png"/>

Alternatively, after dragging an Image component onto the Design view in Flexbuilder, the id and source properties can be set as shown in Figure 9-4. In this example, the id is set to compass and the source is set to compass.png. The transparent portions of the PNG image allow the background gradient to display around the edges of the compass. There is no path required for the image, since itâ&#x20AC;&#x2122;s present in the project directory. The source property can be modified by ActionScript or even bound to a variable that allows for flexibility in changing the source of the image. Because the image is not embedded, it must be published along with the SWF file.

217


218

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure 9-4 The Image Properties for a PNG image

Including an Embedded Image Images can be embedded at compile time by using the [Embed()] and [Bindable] keywords to bind the embedded image to a class. The same <mx:Image> tag is used, but this time the source value is bound to the embedded image class. Listing 9-1 Source Value Bound to Embedded Image Class <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ [Embed(source="compass.png")] [Bindable] public var CompassImage:Class;


Chapter 9:

Working with Media Assets/Deploying

]]> </mx:Script> <mx:Image x="10" y="10" id="compass" source="{CompassImage}"/> </mx:Application>

The Design mode no longer shows the image in Flex Builder, since the image source is now a binding. When run, the image shows up properly, as you can see in Figure 9-5. Since the image is embedded in the SWF, itâ&#x20AC;&#x2122;s not included when the application is published.

Embedding Movies SWF files provide animations in Flash and Flex. They are embedded in a similar manner to image files. The major difference is that embedded SWF files can be treated as MovieClip class instances.

Figure 9-5 The embedded image displays when executed in the application

219


220

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

For example, the MXML code in Listing 9-2 looks very similar to the last example. Listing 9-2 MXML Code for Embedding a MovieClip <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ [Embed(source="assets/animation.swf")] [Bindable] public var Animation:Class; ]]> </mx:Script> <mx:Image id="animation" source="{Animation}"/> </mx:Application>

NOTE Since the source file is referenced as being in the directory assets, an assets directory must be created in your project and the SWF file placed in the directory. Creating an assets directory helps keep your project organized.

This code, however, plays an animated SWF file. It may be helpful to think of how an animated GIF file is inserted using the same HTML as a non-animated GIF file.

Deploying Deploying your Flex application involves generating the appropriate files from Flex and knowing how to integrate them into your existing web files. Since most browsers donâ&#x20AC;&#x2122;t work directly with SWF files, there must be some glue to get everything to work together properly.

Wrappers When Flex applications are deployed, Flex Builder automatically generates HTML and JavaScript code to properly launch the SWF file. The code handles common tasks such


Chapter 9:

Working with Media Assets/Deploying

as validating if the userâ&#x20AC;&#x2122;s browser has the Flash plug-in installed and is of a recent enough release to support the functionality used in the Flex application. If the user does not have a recent enough version, the wrapper will prompt them to download and install the latest version. To see what the wrapper files generated by Flex Builder look like, browse the directory where the current project resides. This could be a path like C:\Documents and Settings\user\My Documents\Flex Builder 3\Project Name\bin, depending on which directory you chose for the project. There are pairs of HTML and SWF files in this directory, along with support files such as AC_OETags.js, history/history.css, history/history.js, and history/historyFrame.html. To view the current settings for how Flex Builder generates the HTML wrapper files, follow these steps: 1. Launch Flex Builder and open an existing project or create a new project. 2. Select Properties from the Project menu. The Properties dialog appears. 3. To display the Flex Compiler options, click the Flex Compiler entry

on the left side of the Properties dialog. The Flex Compiler options appear as in Figure 9-6.

NOTE This is the same properties dialog thatâ&#x20AC;&#x2122;s used to specify using a built-in theme other than the default by modifying the Additional Compiler Arguments field as discussed in Chapter 6.

4. Modify the options within the HTML wrapper section. The settings that can be

changed are listed in Table 9-2. 5. Click Apply to accept the change. The changes will be incorporated the next time the

application is compiled.

221


222

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

HTML Wrapper section

Figure 9-6 The Project Properties Flex Compiler options

Option

Description

Generate HTML wrapper file

Only generates a HTML wrapper file if selected.

Require Flash Player version

Requires the version specified in the entry boxes if selected.

Use Express Installer

The Express Installer simplifies the Flash plug-in upgrade process but requires the user have at least Flash Player 6.0.65 or later installed and JavaScript enabled.

Enable integration with browser navigation

Provides support for sending backward and forward navigation events from the browser to Flash. This can enable Flex applications to respond appropriately to these events using BrowserManager, a module for handling the browser navigation events.

Table 9-2 HTML Wrapper Generation Options


Chapter 9:

Working with Media Assets/Deploying

Ask the Expert Q: A:

Where is the default web root for various web browsers and platforms? Depending on if you’re running IIS or Apache and which operating system you’re using, the default web root folder is placed in different locations. Some common locations: ●

Mac OS X Leopard After enabling “Web Sharing” from the Mac OS X Sharing Configuration panel user’s Sites directories are shared as http://<ipaddress>~username. For example, the user Jon places web files in /Users/Jon/Sites and accesses those web files as http:/localhost/~Jon.

Apache 2.2 on Windows C:\Program Files\Apache Software Foundation\ Apache2.2\htdocs

IIS on Windows C:\Inetpub\wwwroot

Apache on Linux /var/www/html

Publishing Your Application Generally all that’s needed to publish a Flex application is to copy the SWF, HTML, and supporting files from the project directory to a publicly accessible web server. At that point you can modify the existing HTML files to point to the Flex application. It’s also possible to extract the HTML code out of the wrapper file and paste it into the appropriate location of another HTML file if you wish to embed the application in an existing web page. The exact process used to copy the web files varies by web server type, your ISP’s configuration, and the tools they allow you to access the shared web directory. They may use protocols such as FTP, SSH, or even web-based admin interfaces to transfer the files. The FAQ section of your ISP’s customer service site should provide information on publishing your own file to the web server. Flex provides the option of letting users view the source code of your Flex application when they right-click the Flash plug-in window. This feature may be activated while publishing an application.

223


224

Flex 3: A Beginner’s Guide

Ask the Expert Q: A:

What is SSH and do I use it to publish files to a web server? SSH stands for Secure Shell and it is a replacement for the obsolete telnet command. SSH clients vary by operating system but all work similarly. While SSH can be used to begin a shell (terminal) connection, it also includes a protocol called SCP, which stands for Secure Copy. Many commercial web service providers provide access to their web client’s directories via SSH and SCP since they are more secure than using the File Transfer Protocol (FTP), which sends your password across the Internet unencrypted. The following are some examples of SSH clients: Windows: ●

WinSCP is available from http://winscp.net/eng/index.php and provides a graphical interface for transferring files using the SCP protocols

Putty is available from http://www.chiark.greenend.org.uk/~sgtatham/putty/ and provides a graphical interface to the SSH protocol for interactive shell sessions.

Mac OS X: ●

MacSSH is available from http://pagespro-orange.fr/chombier/ and provides a graphical interface to the SSH protocol for interactive shell sessions.

Cyberduck is available from http://cyberduck.ch/ and provides a graphical interface for transferring file using the SCP protocol.

The Unix style command line ssh and scp commands are built into Mac OS X and accessible from the Terminal.

Linux: ●

The ssh and scp commands are included by default with most Linux distributions and are accessed from the shell.

To connect to a SSH server, the hostname or IP address is required as well as a username and password. Many SSH clients include a graphical file browser interface for copying files to the remote server once you’ve connected. If you’re using the command line, scp is used to copy files using the following syntax: scp <source file> <remote user name>@<hostname>:/<destination file path>

For example: scp flex_project jon@example.com:/var/www/flex


Chapter 9:

Working with Media Assets/Deploying

To publish an application and optionally activate this feature: 1. Modify the Export Release Version settings by selecting Export Release Version from

the Project menu. The Export Release Version dialog appears as shown in Figure 9-7. 2. Select the application to modify settings for from the Application drop-down list. 3. Optionally check the Enable View Source check box to enable source viewing;

otherwise, skip to Step 6. 4. Click the Choose Source Files button to display the Publish Application Source dialog

as shown in Figure 9-8.

Figure 9-7 The Export Release Version dialog set to display source

225


226

Flex 3: A Beginner’s Guide

Figure 9-8 The Publish Application Source dialog set to display factorial.mxml

NOTE This publish source process automatically places a viewSourceURL property on the <mx:Application> tag for the published application: <mx:Application xmlns:mx=“http://www.adobe.com/2006/mxml” viewSourceURL=“srcview/index.html”>

1. Place a check mark alongside the files to publish source code for the file. 2. To publish to a directory other than the default of bin-release in the project directory,

click Browse. 3. The Browse For Folder dialog appears. Select a new destination and click OK. 4. Click OK to accept the Export Release Version changes. 5. Click Finish to publish the application to the Export folder.

Selecting the View Source option for the factorial application results in a browser view of the source code as shown in Figure 9-9.

NOTE The Flex compiler automatically adds links to download the source of the application as a ZIP file as well as a link to download the Flex SDK.


Chapter 9:

Working with Media Assets/Deploying

Figure 9-9 The View Source Browser view

Now that media assets can be integrated into the Flex applications and they can be published and integrated to web servers, Flex applications are limited only by your imagination. Have fun playing around with all the possibilities that Flex provides. See the Appendix for a quick reference of commonly used Flex components.

227


This page intentionally left blank


Appendix ActionScript and MXML Reference

229


230

Flex 3: A Beginner’s Guide

ActionScript 3.0 Since Flex programming ultimately boils down to ActionScript code, a high-level reference of global functions and classes is provided here for you to have the information readily accessible.

Global Functions Global functions in Flex aren’t associated with any particular class like other functions. They’re listed in Table A-1 with their return types and what each function does. If you want more information, you can go to this web site: http://livedocs.adobe.com/ labs/flex3/langref/package.html.

Function

Return Type

Purpose

Array

Array

Defines an array.

Boolean

Boolean

Takes an expression as a parameter and returns a Boolean value.

decodeURI

String

Returns the decoded URI string.

decodeURIComponent

String

Returns the decoded URI component as a string.

encodeURI

String

Encodes a URI string by escaping special characters.

encodeURIComponent

String

Encodes a URI component string by escaping special characters.

escape

String

URL-encodes a string. Most characters that aren’t numbers or letters are replaced with their % hexadecimal representation.

int

Number

Returns an integer based in the number passed in. Decimal values are truncated.

isFinite

Boolean

Tests a number to see if its value is finite. Returns true if it is or false for Infinity and Negative Infinity.

Table A-1 Global ActionScript 3.0 Functions


Appendix:

ActionScript and MXML Reference

Function

Return Type

Purpose

isNaN

Boolean

Tests a number to see if its value is NaN (not a number). Returns true if it is or false.

isXMLName

Boolean

Tests the string to see if it is a valid name for an XML attribute or element.

Number

Number

Returns a number based on the parameter. Non-numeric values are represented as numbers. For example, Boolean true becomes 1 or an empty string becomes 0. A string that cannot be converted to a number becomes NaN.

Object

Object

Since every value is considered an Object in ActionScript, Object just returns the object passed to it.

parseFloat

Number

Returns a number derived from converting a string representing a floating-point number.

parseInt

Number

Returns a number based on converting a string.

String

String

Returns a string based on the parameter. Non-string values are represented as strings. For example, Boolean true becomes “true” or for an object the object’s toString function is called.

trace

void

Writes debugging information to the output log.

uint

uint

Returns an unsigned integer value based on the numeric parameter.

unescape

String

Decodes a URL-encoded string by replacing hexadecimal-encoded characters with their original ASCII values.

XML

XML

Returns an XML object based on the object passed in.

XMLList

XMLList

Returns an XMLList object based on the object passed in.

Table A-1 Global ActionScript 3.0 Functions (continued)

231


232

Flex 3: A Beginner’s Guide

Global Constants Global constants in Flex tend to represent numbers that aren’t real. They include the values of infinity and not a number (NaN), as listed in Table A-2.

Constant

Description

undefined

If a non-typed variable has not been set to a value, it’s undefined.

Infinity

Represents the mathematical value of infinity. For example, 1 divided by 0 equals infinity.

-Infinity

Represents the mathematical value of negative infinity.

NaN

A number data type that represents a value that is Not a Number, or NaN for short, similar to null. Comparing two values that are NaN returns false.

Table A-2 Global ActionScript 3.0 Constants

Global ActionScript Classes The Global ActionScript classes are listed in Table A-3.

Class

Description

ArgumentError

This class specifies the type of error if a function call’s arguments do not match the definition of the function.

arguments

The arguments class stores and accesses a function’s arguments.

Array

The Array class is used to manipulate array data and access elements.

Boolean

The Boolean object implements the true and false logical operations.

Class

Class objects are automatically created for any class definition in an application.

Date

Stores data and time information.

Table A-3 Global ActionScript 3.0 Classes


Appendix:

ActionScript and MXML Reference

Class

Description

DefinitionError

Represents an error in the code that attempts to create an identifier that already exists.

Error

Contains detailed error information for errors that occur during the execution of a script.

EvalError

Represents an error in the code that attempts to make an eval() function call. May also occur if a new operator is used on a Function object.

Function

This class represents defined functions. Itâ&#x20AC;&#x2122;s similar to the ActionScript Class class.

int

Manipulates and accesses 32-bit signed integer values.

Math

Implements common mathematical functions like addition and subtraction.

Namespace

Manipulates and accesses namespaces. Namespaces help avoid naming collisions.

Number

Represents floating-point numbers using IEEE-754 double precision.

Object

All classes are derived from the Object class. Itâ&#x20AC;&#x2122;s the root of the ActionScript class hierarchy.

QName

Represents the qualified names of elements and attributes for XML objects.

RangeError

This class stores information about numeric value errors that occur when a value is not in the expected range.

ReferenceError

This class stores information about errors that occur when a program attempts to access an undefined property for a non-dynamic object.

RegExp

This class works with regular expressions. Regular expressions use a standard syntax to describe patterns to match when searching or replacing strings.

SecurityError

Stores error information when a security violation occurs and is caught by Flex.

String

This class is used to represent and modify strings of characters.

SyntaxError

Stores information about an exception if the syntax in the code is erroneous.

Table A-3 Global ActionScript 3.0 Classes (continued)

233


234

Flex 3: A Beginner’s Guide

Class

Description

TypeError

When the data type of an operand doesn’t match the expected data type, this class stores the error details as part of the exception process.

uint

Provides support for representing and working with unsigned 32-bit integers.

URIError

Stores information about exceptions that are thrown if the URI functions are not called with acceptable data.

VerifyError

If a corrupt or otherwise invalid SWF fails to load, this class stores details of the error.

XML

Provides methods and properties for working with XML data objects.

XMLList

Provides methods and properties for working with a list of XML data objects.

Table A-3 Global ActionScript 3.0 Classes (continued)

Language Reference Chapter 3 discussed many of ActionScript’s operators in detail. Here is a summary of the ActionScript’s operators by category.

Operators Operators work on two expressions and return an expression. The basic operators are listed in Table A-4.

Operator

Name

Description

+

Addition

Adds the operand expressions numerically.

-

Subtraction

Subtracts the right-hand expression from the left-hand or negates.

--

Decrement

Decrements the operand by one.

/

Division

Divides the left-hand expression by the right-hand expression.

Table A-4 Operators


Appendix:

ActionScript and MXML Reference

Operator

Name

Description

++

Increment

Increments the expression by one.

*

Multiplication

Multiplies the left expression by the right.

%

Modulo

Performs a division like the division operator but returns the remainder.

Table A-4 Operators (continued)

Arithmetic Compound Assignment Compound arithmetic operators combine an assignment and a mathematical operation involving the variable to be assigned in one step to save typing. They are listed in Table A-5. Assignment operators are used to assign the value of an expression to a variable or attribute. The assignment operator is listed in Table A-6.

Operator

Name

Description

+=

Compound addition assignment

Assigns the variable on the left-hand side of the operator to the value of the left-hand expression added to the right-hand side.

-=

Compound subtraction assignment

Assigns the variable on the left-hand side of the operator to the value of the left-hand expression minus the right-hand side.

/=

Compound division assignment

Assigns the variable on the left-hand side of the operator to the value of the left-hand expression divided by the right-hand side.

*=

Compound multiplication assignment

Assigns the variable on the left-hand side of the operator to the value of the left-hand expression multiplied by the right-hand side.

%=

Compound modulo assignment

Assigns the variable on the left-hand side of the operator to the remainder of the left-hand expression divided by the right-hand side.

Table A-5 Compound Assignment Operators

235


236

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Assignment Operator

Name

Description

=

Assignment

Assigns the value of the right-hand expression to the variable, property, object, or array element on the left hand of the operator.

Table A-6 Assignment Operator

Bitwise Bitwise operators perform binary logic operations at the bit level. They are listed in Table A-7.

Operator

Name

Description

<<

Bitwise left shift

Performs a left shift of the left-side operand by the number of bits specified by the right-side operand after converting both sides to 32-bit integers.

~

Bitwise NOT

Performs a bitwise NOT (flips the bit) after converting the operand to a 32-bit signed integer.

|

Bitwise OR

Performs a bitwise OR (1 if either bit is 1) after converting the operands to 32-bit unsigned integers.

>>

Bitwise right shift

Performs a right shift of the left-side operand by the number of bits specified by the right-side operand after converting both sides to 32-bit integers.

Table A-7 Bitwise Operators


Appendix:

ActionScript and MXML Reference

Operator

Name

Description

>>>

Bitwise unsigned right shift

Performs a right shift of the left-side operand by the number of bits specified by the right-side operand after converting both sides to 32-bit integers. The left-side fill-in bits are always 0, so the sign of the left side is not preserved.

^

Bitwise XOR

Performs a bitwise XOR (1 if either bit is 1 but not both) after converting the operands to 32-bit unsigned integers.

&

Bitwise AND

Performs a bitwise AND at the bit level to the left-hand operand and the right-hand operand after converting them to 32-bit unsigned integers.

Table A-7 Bitwise Operators (continued)

Bitwise Compound Assignment Table A-8 lists ActionScript bitwise operators that also perform an assignment and reference the left-hand value in the bitwise operation.

Operator

Name

Description

<<=

Bitwise left shift and assignment

Bitwise left-shifts the left-side operand by the right-side number of bits.

|=

Bitwise OR assignment

Assigns the left-side variable the value of left side bitwise ORed to the right side.

>>=

Bitwise right shift and assignment Bitwise right-shifts the left-side operand by the right-side number of bits.

Table A-8 Bitwise Compound Assignment Operators

237


238

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Operator

Name

Description

>>>=

Bitwise unsigned right shift and assignment

Bitwise unsigned right-shifts the left-side operand by the right-side number of bits.

^=

Bitwise XOR assignment

Assigns the left-hand side the value of XORing the left-hand side with the right-hand side.

&=

Bitwise AND assignment

Assigns the left-side variable to the left-side value bitwise ANDed to the right side.

Table A-8 Bitwise Compound Assignment Operators (continued)

Comparison ActionScript supports the operators in Table A-9 to compare two operands and return a Boolean value based on the operands.

Operator

Name

Description

==

Equality

Returns the Boolean value of true if both operands are equal.

>

Greater than

Returns the Boolean value of true if the left-hand operand is greater than the right-hand operand.

<

Less than

Returns the Boolean value of true if the left-hand operand is less than the right-hand operand.

>=

Greater than or equal to

Returns the Boolean value of true if the left-hand operand is greater than or equal to the right-hand operand.

<=

Less than or equal to

Returns the Boolean value of true if the left-hand operand is less than or equal to the right-hand operand.

!=

Inequality

Returns the Boolean value of true if both operands are not equal.

Table A-9 Comparison Operators


Appendix:

ActionScript and MXML Reference

Operator

Name

Description

===

Strict equality

Returns the Boolean value of true if both operands are equal and of the same type.

!==

Strict inequality

Returns the Boolean value of true if both operands are not equal and of the same type.

Table A-9 Comparison Operators (continued)

Comments Flex supports three comment styles. They are listed in Table A-10. Operator

Name

Description

/*

Block comment start delimiter

Marks the beginning of multiline comments. Always paired with an ending comment block.

*/

Block comment end delimiter

Marks the ending of multiline comments. Always paired with a starting comment block.

//

Line comment delimiter

Comments out the rest of the current line.

Table A-10 Comment Styles in ActionScript

Logical Operators Logical operators perform logical operations on their operands. They are listed in Table A-11. Operator

Name

Description

&&

Logical AND

Performs a logical AND on the operands and returns true if neither is false.

!

Logical NOT

Performs a logical NOT on the operand and returns the opposite Boolean value.

||

Logical OR

Performs a logical OR on the operands and returns true if either is true.

Table A-11 Logical Operators

239


240

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Other Operators The operators in Table A-12 do not fit any of the prior categories but are useful. Operator

Name

Description

[]

Array access

Creates a new array or multidimensional array using the values supplied. Can also access elements of an array.

There is no operator

as

Determines if the specified expression from the left-hand operand is a member of the right-hand operand.

,

Comma

Evaluates expressions in a list.

?:

Conditional

Shorthand notation for an if statement that operates on the left-hand expression. If the left-hand expression is true, the result is the middle expression; otherwise, it returns the right-hand expression.

There is no operator

delete

Removes the specified object property. Returns true if the property no longer exists after the deletion.

.

Dot

Drills down through a package or class to access its variable, methods, and properties.

There is no operator

in

Returns true if a property is part of an object.

There is no operator

instanceof

Determines if an object is inherited from the specified object by checking the prototype chain.

There is no operator

is

Returns true if an object is compatible with the specified data type, interface, or class.

::

Name qualifier

Specifies the namespace of a property to access.

new

Creates a new instance of a class.

Table A-12 Other Operators


Appendix:

ActionScript and MXML Reference

Operator

Name

Description

{}

Object initializer

Like the new statement, it creates a new instance and also gives it the specified name and value properties.

()

Parentheses

Overrides the default operation execution order for complex expressions. Also specifies the parameters of a function call.

/

RegExp delimiter

Delimits the beginning of a regular expressionâ&#x20AC;&#x2122;s literal value.

:

Type

Specifies a data type for a function parameter type or a function return type.

There is no operator

typeof

Evaluates and returns the type of an expression as a string.

There is no value

void

Returns nothing after evaluating an expression.

Table A-12 Other Operators (continued)

NOTE ActionScript keywords are not capitalized.

String Operators Table A-13 lists ActionScriptâ&#x20AC;&#x2122;s operators for working with string values. The operations include delimiting strings, concatenating them, and a combined concatenation and assignment operator.

Operator

Name

Description

+

Concatenation

Returns the two strings pasted together.

+=

Concatenation assignment

Assigns the left-side operand to the string made by pasting the left-side operand to the right-side operand. Essentially appends the left-side operand to the right-side operand.

Table A-13 String Operators

241


242

Flex 3: A Beginner’s Guide

Operator

Name

Description

String delimiter

Delimits the start and end points of a string and sets them off from being interpreted as a variable name or other element. Double quotes within this string don’t need to be escaped.

String delimiter

Delimits the start and end points of a string and sets them off from being interpreted as a variable name or other element. Single quotes within this string don’t need to be escaped.

\

Escape character

Escapes special characters in a string. For example, \\ includes a backslash and \n includes a newline character.

Table A-13 String Operators (continued)

XML Table A-14 lists operators for working with XML data. Operator

Name

Description

@

Attribute identifier

Names an attribute of an XMLList or XML object.

{}

Braces

Delimits an expression that is evaluated within an XML or XMLList initializer.

[]

Brackets

References an attribute or property of an XML or XMLList object.

+

Concatenation (XMLList to concatenate)

Pastes (concatenates) XMLList or XML values into an XMLList object.

+=

Concatenation assignment (XMLList)

Assigns the left-hand XMLList object expression to the value of the left-hand expression + the right-hand expression.

Table A-14 XML Operators


Appendix:

ActionScript and MXML Reference

Operator

Name

Description

There is no operator

delete(XML reference)

Removes the XML element referenced by the parameter.

..

Descendant accessor

Traverses an XML or XMLList object, accessing its descendant elements. May be used in conjunction with the @ operator to return values.

.

Dot

Traverses an XML or XMLList object by drilling down to the child elements specified before the dot. May be used in conjunction with the @ operator to return values.

()

Parentheses

Evaluates E4X XML construct expressions.

<>

XML delimiter

Delimits the beginning and end of an XML tag literal.

Table A-14 XML Operators (continued)

MXML-Only Components The MXML components in Table A-15 may only be used in MXML, as they do not have corresponding ActionScript code and are implemented by the MXML compiler.

Component

Description

mx:Binding

The <mx:Binding> tag binds data from one object to another.

mx:Component

The MXML <mx:Component> tag defines a new inline cell editor or cell renderer.

mx:Metadata

The <mx:Metadata> tag inserts metadata tags such as search engine keywords that are issued when the application runs.

mx:Model

The <mx:Model> tag declares a data model.

Table A-15 MXML-Only Components

243


244

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Component

Description

mx:Script

The <mx:Script> tag marks the beginning and end of ActionScript code blocks.

mx:Style

The <mx:Style> tag defines styles for the current document and any children.

mx:XML

The <mx:XML> tag defines an XML-format data model object based on MXML input data.

mx:XMLList

The <mx:MXLList> tag defines an E4X XMLList object based on a modified <mx:XML> tag. Unlike its ActionScript equivalent, MXML expression binding in the XML text is supported.

Table A-15 MXML-Only Components (continued)

Keyboard Shortcuts in Flex Builder Frequent tasks in Flex Builder have keyboard shortcuts assigned to them. The most popular are shown in Table A-16.

NOTE The entire list of shortcuts can be seen by pressing SHIFT-CONTROL-L in Flex Builder or SHIFT-COMMAND-L on the Mac.

Name

Windows Shortcut

Alternate Source and Design views

CTRL-` (left mark)

Move Start of Word

CTRL-LEFT ARROW

option-left arrow

Moves to the start of the current word.

Context-sensitive help

F1

F1

Opens context-sensitive help based on the selected workbench element such as a view, dialog box, or tab.

Mac Shortcut

tick command-` (left tick mark)

Table A-16 Flex Builder Multiplatform Keyboard Shortcuts

Function Alternate Source and Design views for the Flex Builder editor.


Appendix:

ActionScript and MXML Reference

Windows Shortcut

Mac Shortcut

Function

Open documentation or API Reference for Flex Builder Plug-in and Stand-Alone, respectively

SHIFT-F2

SHIFT-F2

Opens the language reference help for the currently selected language element. The behavior varies slightly depending on whether Flex Builder is a plug-in or stand-alone installation.

Add Block Comment

CTRL-SHIFT-C

COMMAND-SHIFT-C

Adds a comment block at the current selection point or if a block is already selected, itâ&#x20AC;&#x2122;s placed within a comment block.

Delete Current Line

CTRL-D

COMMAND-D

Deletes the current line.

Add CDATA

CTRL-SHIFT-D

COMMAND-SHIFT-D

Inserts a CDATA block statement at the current selection for embedding ActionScript within an MXML application.

Highlight Matching Bracket

CTRL-SHIFT-P

COMMAND-SHIFT-P

Performs bracket matching by highlighting the matching bracket. Useful for keeping track of matching brackets in longer code blocks.

Content Assist

CTRL-SPACE

COMMAND-SHIFT-SPACE

Makes suggestions about how to complete the current code element using code hinting.

Find All Declarations

CTRL-G

COMMAND-G

Finds all declarations in the workspace.

Find All References

CTRL-SHIFT-G

COMMAND-SHIFT-G

Finds all references to an identifier in the workspace.

Go to Definition

F3

F3

Goes to the definition of a object, including external code definitions.

Name

Table A-16 Flex Builder Multiplatform Keyboard Shortcuts (continued)

245


246

Flex 3: A Beginner’s Guide

Name

Windows Shortcut

Mac Shortcut

Function

Go to Line

CTRL-L

COMMAND-L

Opens the Go To Line window to allow jumping to the specified line number in the editor.

Last Edit Location

CTRL-Q

COMMAND-Q

The last line of edited code is highlighted.

Organize Imports

CTRL-SHIFT-O

COMMAND-SHIFT-O

Alphabetizes any import statements contained in the ActionScript document.

Open Type

CTRL-SHIFT-T

COMMAND-SHIFT-T

Browses through all class types.

Open Resource

CTRL-SHIFT-R

COMMAND-SHIFT-R

Opens the Open Resource window to quickly locate and open a resource in the editor.

Quick Outline

CTRL-O

COMMAND-O

Switches to the Quick mode Outline view.

Table A-16 Flex Builder Multiplatform Keyboard Shortcuts (continued)

Online Resources When developing applications and solving problems, it’s often helpful to have a community of developers to reach out to and share experiences and advice. The following sections break down available resources by category.

Online Communities Table A-17 lists online forums concerning Flex Components, Flex SDK, Flex Builder, and Adobe AIR development. Most of these groups can be joined as an online forum member or by an e-mail distribution list. There are also groups for the Flex-Ajax Bridge as well as the Apache and IIS web modules.

NOTE URLs that are too long to fit into a single table cell are split into two lines. They must be entered as one line in the browser to work properly.


Appendix:

ActionScript and MXML Reference

Group Name

Web Address

Flex Coders Yahoo Group

http://tech.groups.yahoo.com/group/flexcoders/

Flex Components Yahoo Group

http://tech.groups.yahoo.com/group/flexcomponents/

Adobe AIR House of Fusion Forum

http://www.houseoffusion.com/groups/adobe-integrated-runtime/

Adobe AIR Adobe Forum

http://www.adobe.com/cfusion/webforums/forum/ categories.cfm?forumid=72&catid=641&entercat=y

Flex Builder 3 Adobe Forum

http://www.adobe.com/cfusion/webforums/forum/ categories.cfm?forumid=72&catid=651&entercat=y

Flex Builder Linux Adobe Forum

http://www.adobe.com/cfusion/webforums/forum/ categories.cfm?forumid=72&catid=657&entercat=y

Flex module for Apache and IIS Adobe Forum

http://www.adobe.com/cfusion/webforums/forum/ categories.cfm?forumid=72&catid=639&entercat=y

Flex SDK Adobe Forum

http://www.adobe.com/cfusion/webforums/forum/ categories.cfm?forumid=72&catid=650&entercat=y

Flex-Ajax Bridge Adobe Forum

http://www.adobe.com/cfusion/webforums/forum/ categories.cfm?forumid=72&catid=600&entercat=y

Table A-17 Online Forums for Flex and Related Technologies

Documentation Table A-18 lists a variety of documentation sources, including resources on the Adobe site as well as third-party sites.

Site

URL

Flex 3 Release Notes

http://labs.adobe.com/wiki/index.php/Flex_3:Release_Notes

Flex Getting Started

http://www.adobe.com/devnet/flex/ Click the Getting Started tab.

Flex 3 Backwards Compatibility

http://labs.adobe.com/wiki/index.php/Flex_3:Backwards_ Compatibility_Flag

Flex 3 Language Reference

http://livedocs.adobe.com/labs/flex/3/langref/

Flex 3 Developerâ&#x20AC;&#x2122;s Guide

http://livedocs.adobe.com/labs/flex3/html/Part2_ DevApps_1.html

Table A-18 Flex Documentation Resources

247


248

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Site

URL

Flex Developer Center

http://www.adobe.com/devnet/flex/

Open Source Flex

http://www.adobe.com/go/opensourceflex/

Flex.org All Things Flex portal

http://flex.org/

Flex Search

http://flexsearch.org/

RIA Forge

http://www.riaforge.org/

Table A-18 Flex Documentation Resources (continued)

Tools The web sites in Table A-19 include tools that use Flex applications to demonstrate Flex elements that are available, such as Components, Styles, Charts, and Transitions.

Tool

URL

Flex Apps on Flickr

http://www.flickr.com/photos/flexapps/

Flex Component Explorer

http://examples.adobe.com/flex2/inproduct/sdk/explorer/ explorer.html

Flex Chart Explorer

http://flexapps.macromedia.com/flex15/chartexplorer/ explorer.mxml

Flex Style Explorer

http://www.adobe.com/devnet/flex/samples/ style_explorer/

Flex 3 Transitions and Effects Explorer

http://weblogs.macromedia.com/mc/archives/2006/ 04/transition_and.cfm

Flex Ant Tasks

http://labs.adobe.com/wiki/index.php/Flex_Ant_Tasks

flex2ant

http://www.flex2ant.org/

Table A-19 Flex Tools Web Sites


Appendix:

ActionScript and MXML Reference

Quick Reference Sheets The quick reference sheets listed in Table A-20 provide a high-level overview of how the Flex API and framework components relate to each other. They can be viewed in high resolution using Adobe Acrobat 7 or later. They can also be purchased in high-quality poster-sized printouts.

Reference Sheet

Location

AS3 and Flex API

http://www.onflex.org/ted/2006/10/cubewallpaper-as3-and-flex-api.php

ActionScript 3 API

http://www.flex.org/download/AS3API_01.pdf

Table A-20 Quick Reference Sheets for Flex API and Frameworks

Interesting Flex-Based Sites Each of the following sites represent state-of-the-art examples of what can be done using Flex to make other boring data literally jump off the page. Site

URL

Yahoo Maps shown in Figure A-1

http://maps.yahoo.com/

Sherwin-Williams Color Visualizer shown in Figure A-2

http://www.sherwin-williams.com/do_it_yourself/ paint_colors/index.jsp Click the Color Visualizer button.

The Australian Financial Review

http://www.afr.com/home/

Viagga Treno (Italian Train Info) shown in Figure A-3

http://www.viaggiatreno.it/viaggiatreno/vt.html

249


250

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure A-1 Yahoo Maps


Appendix:

Figure A-2 Sherwin-Williams

ActionScript and MXML Reference

251


252

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

Figure A-3 Viagga Treno


Glossary

253


254

Flex 3: A Beginner’s Guide

A ActionScript This language was initially designed for controlling simple 2-D vector animations created in Flash. Now its functionality is for creating web-based games and RIAs with streaming media such as audio and video. Ajax (Asynchronous JavaScript and XML) There are free and Open-source distributions of Ajax, which is a web development framework that is used to create interactive web applications. Using Ajax usually increases the web page’s speed, functionality, interactivity, and usability. AMF (Action Message Format) A format based on the Simple Object Access Protocol (SOAP). It’s used primarily to exchange data between a Flash application and a database, most likely using a Remote Procedure Call. AMF messages contain a body portion that holds the error or response and then gets ported to an ActionScript object. anonymous function variable.

Looks like a mix between defining a function and setting a

Apache The most popular web servers in use on the Internet. Apache is named after “a patchy,” meaning in its beginning there were many code fixes. It is supported across most major operating systems. Its main rival is Microsoft’s Internet Information Services (IIS). API (Application Programming Interface) Is a source code interface that an OS or library supports to enable requests for services to be made of it by software applications. application server Is a software engine that delivers applications to users’ computers. An application server handles most of the business logic and data access of the application. The benefit of this is the ease of application development. ASP (Active Server Pages) Microsoft’s server-side script engine for dynamically generated web pages. It’s an add-on to Internet Information Services (IIS), which is similar to Apache. ASP pages are written in VBScript or JScript. Atom A syndication format written in XML used for web feeds, and a publishing protocol (APP is the acronym, but it is referred to as AtomPub for short) for creating and updating web resources.


Glossary

B beta Is the first software version released outside the development group to enable evaluation and real-world testing of the software. Delivering a beta version to users is called a beta release. Beta-level software includes all features documented in the UIDD but has problems, issues, and bugs that havenâ&#x20AC;&#x2122;t been ironed out and wonâ&#x20AC;&#x2122;t until GA. Boolean A Boolean value has two values: one and zero, which are equivalent to true and false. This is a binary numeric datatype of only one digit, or bit. These values restrict the allowed value range for certain operations. Some of the datatypes are AND, &, *, OR, |, +, XOR, EQV, =, and = =, as well as some other symbols. browser What you use to interact with the Internet. Some common browsers include Mozilla Firefox, Netscape Navigator, and Microsoft Internet Explorer. Different browsers support different levels of audio, animation, and graphics. build Consists of compiling and debugging. You may be able to squeak by without using the debugger.

C Captivate An e-learning Windows-based Instructional Design authoring tool to create software demonstrations, simulations, branched scenarios, and randomized quizzes in the .swf file format. It can also take files and transport them to SWF files for Flash. case sensitive Upper- and lower-case letters mean something to the equipment, usually a computer or a software application, processing the data. Therefore, Flex sample_text is a different variable than Sample_Text. client A program that provides an interface to remote Internet services, like web mail, telnet, and other things. Code Editor This view enables you to write MXML, ActionScript, and CSS code. The Code Editor gives you code hinting and formatting and a design mode where you can visually define your Flex application layout; additionally, you can complete integration with the Flex Builder debugging tools, and there are syntax error checking and problem reporting.

255


256

Flex 3: A Beginner’s Guide

ColdFusion An Adobe application server and software development environment that’s used for development of computer software and dynamic web sites. ColdFusion is a similar product to Microsoft ASP.NET, J2EE, or PHP. compile Compiling for Flex creates the common binary SWF file that the Flash player will use to execute your application. constructors These are special methods that are called when instantiating a new instance of an object. They are named the same as their class name. CSS (Cascading Style Sheets) A stylesheet hypertext markup language used to describe the presentation of a document. It’s used with HTML and XHTML, that can be applied to XML.

D database A set of information organized for storage, search, retrieval, and insertion. Normally used as a back end to a front-end software application. datagrid A component that shows a variable amount of data in a table-like format. Multiple columns are supported as well as sourcing the data from a data source. data type default

Some basic types are numbers, strings, and Booleans.

The standard or normal-state settings for a software application.

design and configure The first step in designing any application is determining what you want the application to do. Once you’ve figured out what you want your application to do, you can begin to select which API functions to use in order to build your application. Selecting the right plan of attack can make the difference between an easy, clean implementation or a lot of extra work. DHTML (Dynamic Hypertext Markup Language) Creates dynamic web pages. It’s a collection of technologies such as HTML, JavaScript, CSS, and DOM. directory

A folder that contains files.

DMS (Data Management Service) Provides data synchronization between real-time data updates, on-demand data paging, data replication, and integration through adapters


Glossary

to data. You can create applications that work with distributed data, and manage large collections of data as well as nested data relationships.

DOM (Document Object Model) A platform- and language-independent standard model for HTML, XML, and other related formats. You donâ&#x20AC;&#x2122;t need a web browser to render DOM-based HTML, but DOM is required by JavaScript in order to dynamically inspect and modify web pages. domain name The Internet naming schema. An Internet machine is identified by a series of words from more specific to more general, separated by dots. domain name server (DNS) A machine loaded with software to translate a domain name into the corresponding numbers of the IP address. downloading To obtain information from a computer other than yours that will eventually display on your own screen. DTD (Document Type Definition) One of several SGML and XML schema languages, also used to describe a document that is authored in the DTD language. Dreamweaver A web development tool that produces HTML pages. It also supports a wide variety of formats, including PHP and ColdFusion.

E Eclipse An open-source software Integrated Development Environment (IDE) platform written in Java. Itâ&#x20AC;&#x2122;s frequently used for Java development but is flexible to support a wide range of programming languages, including, of course, Flex. e-mail An electronic message, text, or data sent from one machine or person to another machine or person. encapsulation Similar to the process of putting your code into functions to make it easier to reuse and organize, but encapsulation takes it one step further by creating a clear boundary between existing code and new code that you create. event handlers Define a block of code to execute based on certain events. Events can include error conditions or user-initiated actions such as a mouse click.

257


258

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

expressions An instruction that executes something that returns a value. Expressions are combinations of variables and operators that evaluate to a single value such as a number, a Boolean value, or an object.

F FDS (Flex Data Services) This product offering is now called Live Cycle Data Services. See LiveCycle Data Services. Flash Adobe Flash Professional is an IDE, while the Flash Player is a virtual machine used to run, or parse, created Flash files. Flash can refer to the authoring environment, the player, or the application files. Flex Adobe Flex is a software development kit and an IDE released by Macromedia in 2004 to support development and deployment for cross-platform, Rich Internet Applications based on Macromedia Flash. Adobe open-sourced the Flex 3 SDK in May 2007. For Loop Iterates through a range of values that you specify in its parameters. You can access the variable with the current value of the iteration in the code block that repeats. FTP (File Transfer Protocol) Enables an Internet user to transfer electronic files between remote computers and the userâ&#x20AC;&#x2122;s computer. functions An organizational tool for grouping code together that performs an action as a whole. They take parameters and return an optional single value. Functions prevent having to retype and maintain segments of code that you use more than once in addition to organizing your code. Without functions your code would have to be in a long list like the old school programming language BASIC.

G GA (General Release) This is when a software application has been through alpha and beta testing and is the general release of the software with minor bugs, all features implemented, and bug fixes corrected from the reports delivered during alpha and beta testing. GA stands for General Acceptance, meaning that the software is ready for sale and distribution. gateway

A computer that forwards and routes data between two or more networks.


Glossary

getter and setter methods It is common practice for object-oriented classes to store information in protected properties and force the users of the class to access those values using defined get and set functions that work on the instance properties. They enforce the encapsulation principles of object-oriented design. GUI (Graphical User Interface) An interface that allows users to work with a computer. This includes software applications such as Microsoft Word that have graphical elements as opposed to command-line text editors like vi.

H hacker Someone who messes with computer systems to see how much could be accomplished; usually someone that wants to create viruses or other problems. A hacker can also be someone whoâ&#x20AC;&#x2122;s just interested in how things work, unlike a malicious user who is simply up to no good. See malicious user. host computer This is a computer that directly provides service to a user, in contrast to a network server, which provides services to a user through an intermediary host computer. HTML (Hypertext Markup Language) The coding system to format and link documents on the World Wide Web and intranets. There isnâ&#x20AC;&#x2122;t a rigid tagging system for HTML as there is for XML and other languages.

I IDE (Integrated Development Environment) A software application that programmers use for software development. An IDE usually consists of a source code editor; a build automator, a compiler or interpreter, and a debugger. Oftentimes there is a version control system and other graphical interface tools wrapped into the IDE as well. Because programming has become way more complicated, modern IDEs also integrate a class browser, an object inspector, and a class hierarchy diagram, for use with OO development. If statement Also formally known as an If Then Else statement, as the else and else if portions are optional. It allows the program execution to branch based on the evaluation condition you specify.

259


260

Flex 3: A Beginner’s Guide

IIS (Internet Information Services) Microsoft’s web server. It’s supplied with the professional editions of Windows. While not as popular as Apache, it continues to gain market share. inheritance Means that you can modify how a class works without modifying the super class itself. The modified class derives methods and properties from the super class automatically. instance variable A non-static class variable. The variable’s value is unique to whichever instance of the class has been instantiated. This is useful for tracking data that is relevant to the current instance such as the screen coordinates of an object, as you wouldn’t want to store that information at the class level. A subclass cannot override a class’ instance variables. instantiation

Is where an object is created based on a class.

Intellij The first Java IDE with a set of integrated refactoring tools that enable programmers to rapidly redesign their code. IP (Internet Protocol) The Internet standard protocol providing a common layer over dissimilar networks, which is used to move packets among host computers and through gateways. IP address The alpha or numeric address of a computer connected to the Internet. Also called “Internet address.”

J J2EE (Java Platform Enterprise Edition) J2EE has more libraries than regular Java to create applications that run on an application server. Normally, portable, scalable enterprise applications are created that integrate with, now dated, Legacy applications. The extra components that J2EE has include Enterprise JavaBeans, portlets, JSP (Java Server Pages), servlets, and other web technologies. Java Currently, Java is an open-source programming language. It gets most of its syntax from C and C++, but its own object model is less complicated than those two languages.


Glossary

JavaFX A group of products developed by Sun Microsystems. The products are used to create RIAs. Right now, JavaFX consists of JavaFX Script and JavaFX Mobile, and future products are planned to accompany the current offering. JSP (Java Server Pages) This technology allows software developers to dynamically generate XML or HTML per a web clientâ&#x20AC;&#x2122;s request. The JSP syntax adds additional tags that are similar to XML, called JSP actions, that can be used for built-in functionality. You can also create JSP tag libraries that act as extensions of XML or HTML tags.

K keyboard events Events related to the user pressing a key. They are associated with an event handler to perform a specific action when the keyboard event happens.

L LiveCycle Data Services Formerly called Flex Data Services (FDS), this is an J2EE application for Flex along with a solution component of Adobe LiveCycle. This provides several services such as data push, publish, and subscribe for Flex applications. looping Defines what steps your program follows by using statements such as IfElseThen or switch. Looping uses either for or while.

M malicious user This is a user that looks for mistakes and weak points in the design of a computer system or application and develops exploits to take advantage of them either for personal or financial gain. manifest file Tells the Flex compiler how to find ActionScript code that corresponds to MXML tags in namespaces. Message Service A messaging service for real-time applications. You create applications that send and receive messages from other applications, such as Flex and Java Message Service (JMS). methods Another name for a function if itâ&#x20AC;&#x2122;s part of a class. Methods are another tool for organizing your code.

261


262

Flex 3: A Beginnerâ&#x20AC;&#x2122;s Guide

mouse events Events that relate to the user clicking or hovering over an object. They are associated with an event handler to perform a specific action when the mouse event happens. MXML (Macromedia eXtensible Markup Language) This is used to lay out the visual components of software applications, used to implement complex business logic and RIAs. MXML is used with the Flex Server, which compiles the language into SWF files. Adobeâ&#x20AC;&#x2122;s Flex Builder IDE and Flex SDK also generate SWF files from MXML for use without the Flex Server.

N navigation bar A set of words or images that display on web sites with links to different sections of the site. Navigator view In Flex Builder this view displays all of the projects in your workspace and all of the resources, including folders and files, within your projects. numbers

Stores numeric values. They can be used with the usual mathematical operations.

O objects

A special datatype that can hold multiple pieces of data in a predefined format.

offline

Being unconnected to a remote host.

online

Being connected to a remote host.

OOP (object-oriented programming) A collection of objects, which is seen as a list of instructions for the computer. With OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object is an independent entity that has a distinct role or responsibility. OpenLaszlo An open source platform for the development and delivery of RIAs. The platform consists of the LZX programming language and the OpenLaszlo Server. Open Source A set of principles and practices that promote access to the design and production of software, programming languages, and knowledge. PHP is an Open-source


Glossary

technology, just like Linux. Users collaborate and make changes and adjustments to code that everyone can download, use, and also comment on to enhance the software.

OS (operating system) The software that manages sharing of computer resources, as well as providing computer programmers with an interface to access those resources.

P packages Provide a way of grouping classes together with a common name. Use the package statement when declaring a class to make it part of a package. PDF (Portable Document Format) An Adobe-copyrighted format that allows a document to be saved in order to look a certain way, no matter what machine is used to display it. You must use a PDF viewer such as Adobe’s Acrobat reader, a free, downloadable program, to display the file. PHP A programming language designed to create dynamic web pages. PHP is used in server-side scripting but can be used from a command-line interface or in stand-alone graphical applications. PKZIP An application that compacts multiple files into one file with the extension of .zip. It also extracts files that are in a ZIP file. These files are easily transferred over the Internet and aren’t corrupted by Internet transfer. WinZip is a commonly used ZIP application. polymorphism The ability of a member function to act differently depending on the type of object that implements the method. The method must have the same name, and it’s implied but not required that the functionality be similar. Problems view This view displays your syntax and other compilation errors that are detected by the compiler. By default the compiler builds your Flex project each and every time you make a change to it, so you get almost immediate feedback as you create your code. protocol A mutually determined set of formats and procedures governing the exchange of information between systems.

263


264

Flex 3: A Beginner’s Guide

Q query A formal request for data. In the realm of the web and programming, queries are associated with the Q in SQL (Structured Query Language). They ask the database what matches the query. See SQL.

R RIA (Rich Internet Application) Applications on the web with features and functionality of traditional desktop applications. RIAs run in a web browser and usually don’t require software installation or can run locally in a secure sandbox environment. RPC services A call and response system in order to access external data. It helps you create applications that make remote services requests, and after they’re processed, data is returned to your Flex application. RSL (Run-Time Shared Libraries) Used to reduce the size of your applications. RSLs are SWF files that contain code used as a shared library between different application SWF files. RSS (Really Simple Syndication) Web feed formats used to publish frequently updated content such as blog entries, news headlines, or podcasts.

S sandbox

A test area for experimenting with code.

SDK (Software Development Kit) A set of development tools that enables programmers to create applications for software packages, web applications, hardware platforms, operating systems, and the like. SGML (Standard Generalized Markup Language) A descendant of IBM’s Generalized Markup Language (GML). SGML supports a variety of markup syntaxes used for numerous applications. By changing the SGML declaration, you don’t need to use angle brackets, < >, which are common in HTML and XML.


Glossary

Silverlight Silverlight competes with Flash and the presentation components of Ajax. It’s a proprietary runtime environment by Microsoft for browser-based RIAs, which provide animation, vector graphics, and video for the Windows Presentation Foundation. It’s available for both Windows and Mac OS X. SQL (Structure Query Language) Defines a language that is adept at describing which data should be returned for a relational database when executing a query. SQL queries are interpreted and processed by the relational database engine. SQL provides a standard language for operating with a wide range of databases. SQL Adapter Simplifies the application development using Data Management Services without having to write any server-side Java code. Software developers use the SQL Adapter to automatically detect changes made on the client and conflicts. SSL (Secure Socket Layer) Provides secure communication on the Internet for such things as purchasing on the web, browsing, e-mail, faxing, and instant messages, as well as any other data transfers, like FTP. strict data type To create or assign a strict data type variable, you’ll need to add a colon (:) and the data type after the variable name. The statement must also begin with the var keyword. strings These are defined by either using a pair of single quotes (') or double quotes (") to mark the beginning of a string and its end. SWC (Shock Wave Component) An archive file that can be called a class library for Flex components. SWC files contain a SWF file and a catalog.xml file. Flex applications extract the SWF file from the SWC file and use its contents when the application refers to resources in that SWC file. The catalog.xml file is a content list of the entire component package and its individual components. SWF (Small Web Format or Shockwave Flash) Pronounced as swiff, SWF is the extension files that are generated by Flash or Captivate. SWF files usually contain animation or applets that have different degrees of functionality and interactivity. Animated display graphics and DVD menus for movies can also be SWF files. switch statement Executes the block of code from a case that matches the value of the expression specified after the switch keyword. Then, within curly brackets, each potential value to check for is listed after case keywords.

265


266

Flex 3: A Beginner’s Guide

T TCP/IP (Transmission Control Protocol/Internet Protocol) A set of protocols that perform the transfer of data between two computers. TCP monitors and ensures correct data transfer. IP receives the data from TCP, breaks it up into packets, and sends it to its destination. telnet An Internet client that connects to other computers, making yours a virtual terminal of the remote computer. Among other functions, it enables a user to log in to a remote computer from the user’s local computer.

U UIDD (User Interface Design Document) A document created by the designer who creates, designs, and writes the specifications for a software application and puts them all into one document for computer programmers to model and create the application from. upload

To send a file or message from your computer to another.

USB (Universal Serial Bus) A connection to a computer. A USB hub enables you to connect multiple peripherals. If you have a USB iPod, printer, modem, and CD-ROM drive, you could plug only one into the USB port and connect the rest by USB cables in a chain.

V valid A valid document conforms to some semantical rules. These are either user-defined or included as an XML schema or DTD. If a document contains an undefined tag, then it’s not valid and a validating parser can’t process it. variable names Cannot contain spaces, but underscores are often used instead to split up words in a variable name. Variables cannot be the same as reserved words, which are ActionScript keywords such as for, while, and if. variables There are several standard data types of variable values, including numbers, strings, arrays, and objects.


Glossary

W W3C (World Wide Web Consortium) The main international standards organization for the World Wide Web. Sir Tim Berners-Lee, the primary author of the original HTML specifications, heads W3C. well-formed An XML conformity. If your document is formed correctly, it conforms to XML’s syntax rules. For example, if an element has an opening tag with no closing tag and isn’t self-closing, it’s not well-formed. This then means that a conforming parser isn’t allowed to process the document. while loop

Executes its block of code until the while condition is false.

X XML (eXtensible Markup Language) A specification developed by the W3C. It enables developers to create their own customized tags, similar to HTML. XML namespaces A way of naming your XML elements to avoid conflicting with the names another XML developer may choose. XUL (XML User Interface Language) Pronounced zool, XUL is an XML markup language produced by Mozilla for use with browsers such as Firefox. Currently, the only complete implementation of XUL is the Gecko layout engine. XUL relies on CSS, DOM, and JavaScript.

Z ZK Framework An open-source, Java and Ajax web application framework that needs little to no programming.

267


This page intentionally left blank


Index Symbols ( : ) colon, 57 ({ }) curly brackets, 49, 60, 68 ( " ) double quote, 55–56 ( = ) equals sign, 57 ( ' ) single quote, 55–56

A absolute positioning, 87–89, 99 access. See data access ActionScript case sensitivity of, 54 defined, 3 Flex SDK including, 23–24 global classes, 232–234 global constants, 232 global functions, 230–231 OOP, 70–75 overview of, 4, 50 proper syntax, 52–53 timeline, 51–52 using expressions, 57 using variables, 54–57 ActionScript, operators, 234–243 assignment, 236 basic, 234–235 bitwise, 236–237 bitwise compound assignment, 237–238 comments, 239 comparison, 238–239 compound assignment, 235 logical, 239 miscellaneous, 240–241 string, 241–242 XML, 242–243 Additional Compiler Arguments field, 148 Adobe Flex 2.01, 15 Adobe Flex 3, 15–16 Aeon Graphical theme, 147 Ajax, 13 Allocation Trace panel, 181, 193–195 anonymous functions, 61–62 Apache/IIS default web root folders for, 223

Flex module, 42–46 Runtime Module, 24–25 API, Flex, 11 Apollo project, 12 appearance, modifying, 139–157 CSS Property Inspector, 144–145 enhanced constraints, 142–144 overview of, 140–141 skins, 141–142, 154–157 styles, 141–142, 149–154 themes, 145–150 application container, 87, 91 arrays, 92–93 assets. See media assets assignment operator, ActionScript, 236 attributes, class, 68 attributes, Menu control, 106 audio. See sounds

B base state, 117 basic operators, ActionScript, 234–235 behaviors composite effects, 133–134 creating, 129–131 defined, 117 working with, 131–133 [Bindable] keyword, 218–219 binding variables, 117, 134–138 bitwise compound assignment operators, 237–238 bitwise operators, 236–237 body, class, 68–69 bookmarks, browser, 122 Boolean values, 56 break keyword, 62 breakpoints, 84–86, 202–206 Breakpoints view, Flex Debugger, 86 browsers default web root folder for various, 223 using bookmarks, 122 using BrowserManager, 123 building, Flex applications, 17 buttons, linking to data, 175–178

269

C Cascading Style Sheets. See CSS (Cascading Style Sheets) case keywords, switch statement, 62 case sensitivity, ActionScript, 54 Check menu item, 105 class keyword, 51, 67–68 classes ActionScript 3.0 global, 232–234 functions as methods within, 58, 70–75 OOP programming and, 67–70 sound, 213 specifications, 75–76 click property, 175–176 Code Editor defined, 181 Flex Debugger, 84 Flex Developer, 82–83 colon ( : ), 57 commands, fdb debugger, 203–206 comments, 239 comparison operators, 238–239 compc (Component) compiler, 17 compiling, 17, 46 components building Flex applications with, 86 used only in MXML, 243–244 using containers, 86–90 using controls. See controls composite effects, 133–134 compound assignment operators, 235 concatenation, 55–56 Connection Established dialog, 184–185, 194 Console view, Flex Debugger, 86 constants, global, 232 ConstraintColumns constraint, 142–144 ConstraintRows constraint, 142–144 constraints, 87–89, 142–144 constructors, 67, 71–72 containers, 86–90, 142 content-sized constraints, 143 controls adding to application for data display, 167 arrays, 92–93 data provider, 94 Label control, 104–105 list of all Flex, 95–96


270

Flex 3: A Beginner’s Guide

controls (continued) Menu control, 94–96, 105–106 modifying, 96–99 overview of, 90–92 placing using containers, 86–90 text, 93–94, 100–104 conversion, MXML, 67 createMenu( ) method, 107 cross-domain file, 160, 162–163 CSS (Cascading Style Sheets) external, 154 graphical skinning using, 154–157 setting style properties, 142 as theme format, 146 CSS Property Inspector, 144–145 curly brackets ({}), 49, 60, 68 currentState property, 118–119

saving and loading profiling data, 187–188 with trace( ) function, 206–207 types of debuggers, 18 declaration, variable, 54 Deep Linking, 122–123 default web root folder, 223 deployment, 18–19 development, Flex Developer, 82–84 DHTML (Dynamic HTML), 13 directory, Flex SDK structure, 39 DMS (Data Management Service), 6 Document Object Model (DOM), 13–14 documentation, online resources, 247–248 DOM (Document Object Model), 13–14 double quote ( " ), 55–56 DPKG removal, of Flash plug-in, 38–39

D

E

data access local vs. remote data, 161 overview of, 160 security implications, 161–164 XML HTTP Service Requests. See XML HTTP Service Requests Data Management Service (DMS), 6 data provider controls, 94, 106–107 data types, ActionScript, 54–57 dataField property, DataGrid, 173 DataGrid control adding for data display, 167–169 linking TextArea to, 175 linking to data, 173–174 RSS feeds and, 160 skins for, 141 dataProvider property, DataGrid control, 173 dataProvider property, MenuBar control, 109–110 Debug view, Flex Debugger, 86 debugging Allocation Trace panel, 194–195 with fdb, 200–206 Flex Debugger, 84–86 Launch dialog, 198–200 Live Objects panel, 188–190 Loitering Objects panel, 191–193 Memory Snapshot panel, 190–191 Object References panel, 193 Performance Snapshot panel, 196–197 profiling, 181–186

Eclipse IDE, and Flex Builder, 23 editable property, text-based controls, 102 Effect Properties panel, 129–130 effects composite, 133–134 creating transitions, 117, 125–128 defined, 116 overview of, 124 @Embed keyword, 156 [Embed( )] keyword, 218–219 embedded media assets images, 218–219 movies, 219–220 runtime-referenced vs., 211 sounds, 213–216 encapsulation, 67 enhanced constraints, 142–144 equals sign ( = ), 57 error messages, profiling, 182–186 event handlers, 65–67, 123–124 Expessions view, Flex Debugger, 86 Export Release Version dialog, 225–226 expressions, 49, 57 extends keyword, 51, 67, 75 Extensible Markup Language (XML), 50, 242–243 external CSS files, 154

F fdb command-line debugger commands, 203–206 debugging with trace and, 206–208

defined, 18, 181 launching, 201–202 overview of, 200–201 Filters button, Live Objects panel, 189–190 final keyword, 74 fixed-sized constraints, 142 Flash, origins of Flex, 3–4 Flash Player downloading Flex SDK, 38 installing Flex SDK, 40 limitations of, 12 security features, 20 support for plug-in, 14 Flash Player Debugger, 18, 201–202 Flex ActionScript and, 4 cross-platform support with single binary, 14 how it works, 16–20 HTML/AJAX vs., 13–14 limitations of, 12–13 LiveCycle Data Services, 5–10 MXML and, 4–5 origins of, 3–4 strengths of, 10–11 versions, 14–16 Flex 2 SDK, 15 Flex-Ajax Bridge, 14 Flex Builder containers, 86–90 controls. See controls debugger, 18 distribution, 23 generating SWF files from MXML with, 49 installing Flex with, 22–25 keyboard shortcuts in, 244–246 modes, 81–86 projects, 30–37 purchasing, 15 running applications, 80–81 using LiveCycle Data Services with, 8–10 using proxy, 163–164 working with, 80–81 flex-config.xml file, 76 Flex Data Services, 15–16 Flex Debugger perspective, 84–86, 181 Flex Developer perspective, 82–84, 155 Flex Events, 131 Flex Module, Apache/IIS, 42–46 Flex Online Compiler, 6–8 Flex SDK, 49 Flex Server, 49


Index flow control If statement, 61 looping, 63–65 overview of, 61 switch statement, 62 <font> tag, 101 fonts, changing for controls, 99 For Loop, 64–65, 67 formats supported image, 212 theme, 146 fromState property, transitions, 125 function keyword, 70–71 functions ActionScript 3.0 global, 230–231 anonymous, 61–62 defining, 58 defining within classes as methods, 70–75 named, 13–15 overview of, 57–58 testing output, 58–59

G garbage collection, 182–186, 188–190 getter method, 74–75 getting started Apache/IIS Flex module, 42–46 Flex Builder projects, 30–37 general requirements for SDK, 37–42 installing Flex, 22–25 installing Flex Builder, 25–30 GIF (Graphics Interchange Format), 212 graphical skinning, 154–157 Graphics Interchange Format (GIF), 212

H Halo theme, 147 heap, 193 HTML Flex vs., 13 MXML vs., 49 wrapper files, 220–222 htmlText property, 100–104, 175 HTTP Service Requests. See XML HTTP Service Requests

I Ice theme, 147 id property, referenced images, 217–218 IDE (integrated development environment), 23, 24

If statement, 61 If Then Else statement, 61 IIS. See Apache/IIS images embedded, 218–219 referenced, 217–218 supported formats, 212 import command, Menu control, 108 Import dialog, 184–185 Import Wizard, 141 infinite loops, 63 inheritance, 75 inline styles, 150, 156 installation Flex Builder, 25–30 Flex SDK, 37–42 overview of, 22–25 testing compiler module, 46 instance variables, 70 instantiation, 72–73 Institutional theme, 147–148 integrated development environment (IDE), 23, 24 iteration, and For Loop, 64–65

J Java, Flex SDK requirements, 37 JavaScript ActionScript derived from, 50–51 Flex and, 13–14 wrapper files, 220–222 Joint Photo Experts Group (JPEG) format, 212 JPEG (Joint Photo Experts Group) format, 212

K keyboard shortcuts, Flex Builder, 244–246

L Label control, 104–105 Launch dialog, 198–200 layout, 87–89, 167–169 LCDS (LiveCycle Data Services) features, 16 overview of, 5–8 proxy system, 163 using with Flex Builder, 8–10 LinkButton control, 167–169, 176–178 Linux, 223–224 Live Objects panel, 180, 188–190

LiveCycle Data Services. See LCDS (LiveCycle Data Services) local data, 160–161 local style definition, 150–153 logical operators, 239 Loitering Objects panel, 181, 191–193 looping defined, 63 For Loop, 64–65 while loop, 63–64 loose typing, 51

M Macintosh OS X default web root folder for, 223 installing Flex Builder in, 28–30 SSH clients, 224 using Apache/IIS Flex Module, 42–46 manifest file, 76–77 maskSkin, 141 media assets, 209–227 deploying applications and, 18–19, 220 embedding images, 218–219 embedding movies, 219–220 embedding vs. runtime referencing, 211 managing, 211 overview of, 210 publishing application, 223–227 referenced images, 217–218 runtime referencing, 211 sounds, 213–217 supported media types, 212 wrappers, 220–222 memory management Allocation Trace panel and, 194–195 garbage collection for, 182–186 Live Objects panel and, 188–190 Loitering Objects panel and, 191–193 overview of, 180–181 Performance Snapshot panel and, 196–197 Memory Snapshot panel, 180, 190–191 Menu control attributes, 106–107 creating, 107–108 defined, 94 item types, 105 MenuBar control, 109–112 menu controls, 94–96

271


272

Flex 3: A Beginner’s Guide

MenuBar control, 94, 109–112 Message Service, LiveCycle Data Services, 6 methods defined, 58 instance, 73–74 instantiation, 72–73 overview of, 70–72 static, 74–75 modes, Flex Builder, 81–86 movies, embedding, 219–220 Moxie, 15–16 multilevel nested arrays, 106–107 Multimedia eXtensible Markup Language. See MXML (Multimedia eXtensible Markup Language) mx prefix, defined, 77 <mx:AddChild> tag, 119 <mx:Application> tag, 91, 147, 170 <mx:Binding> tag, 137 <mx:DataGrid> tag, 173 <mxDataGridColumn>, 173 <mx:HttpService> tag, 170 <mx:Image> tag, 217 <mx:Label> tag, 104 <mx:LinkButton> tag, 175–176 <mx:MenuBar> tag, 109 mxml-manifest.xml file, 77 MXML (Multimedia eXtensible Markup Language) components only for, 243–244 conversion, 67 Flex SDK and, 23–24 LiveCycle Data Services with Flex Builder and, 9 namespaces, 76–77 overview of, 4–5 principles of, 49–50 mxmlc (Application) compiler, 17 <mx:parallel> tag, 125–126, 133–134 <mx:PopUpMenuButton> tag, 111 <mx:Script> tag, 53, 154 <mx:sequence> tag, 125–126, 133–134 <mx:SetEventHandler> tag, 123 <mx:SetProperty> tag, 123 <mx:SetStyle> tag, 123 <mx:State> tag, 123 <mx:Style> tag, 146 <mx:TextArea> tag, 175 <mxTransition> tag, 125–128 <mx:XML> tag, 106–109

N named functions, 59–61 namespaces, MXML, 76–77

naming conventions functions, 59–61 MXML namespaces, 76–77 variables, 54–55 navigateToURL function, 175 Navigator containers, 89–90 Navigator view, Flex Developer, 83–84 New Flex Project dialog, 31–33 new keyword, 72 Normal menu item, 105 numbers, ActionScript, 55

O object oriented programming. See OOP (object oriented programming) Object References panel, 181, 193 objects manipulating in Flex, 11 as special data type, 54 online resources documentation, 247–248 interesting Flex-based sites, 249–252 online communities, 246–247 quick reference sheets, 249 tools, 248 OOP (object oriented programming) class specifications, 75 classes, 67–70 defined, 67 encapsulation, 67 Flex framework using, 49 inheritance, 75 methods, 70–75 Open Profile Folder button, 187–188 open source framework, Flex, 11 operators. See ActionScript, operators overriding, HTML tags, 101

P packages, 68, 188–190 Panel container, 167–168 PanelSkin programmable skin classes, 141 partitioning, enhanced containers, 142 percentage-sized constraints, 143 percentage values, sizing controls, 98 Performance Snapshot panel, 181, 196–197 perspectives Flex Debugger, 84–86 Flex Developer, 82–84

overview of, 81–82 Profile, 182, 199–200 PNG (Portable Network Graphics) format, 212 PopUpMenuButton control, 94, 110–112 Portable Network Graphics (PNG) format, 212 positioning, controls, 99 Problems view, Flex Developer, 83 Profile button, 183–184, 198–200 Profile External Application, 199–200 Profile panel, 187–188 Profile perspective, 182–186, 199–200 profiling defined, 180 overview of, 181–186 saving and loading data, 187–188 ProgressBar, 141 projects creating test, 31–37 Flex Builder, 30 properties Label control, 104–105 referenced images, 217–218 sizing controls, 97–98 state, 123 style, 142, 151–152 TextArea, TextInput and RichTextEditor controls, 101–102 Property Inspector, CSS, 144–145 prototypes, 67 proxy creating application using, 166 defined, 160 ensuring security with, 163 in Flex Builder, 163–164 Publish Application Source dialog, 225–226 publishing application, 223–227

Q quick reference sheets, online resources, 249

R Radio menu item, 105 Really Simple Syndication feeds. See RSS (Really Simple Syndication) feeds referencing, bound variables, 135 relativeTo attribute, <mx:AddChild> tag, 119


Index remote data, 160, 161. See also XML HTTP Service Requests Remote Procedure Call (RPC) request, 6. See also XML HTTP Service Requests Remove All Breakpoints, 85 reserved words, 54, 60 return keyword, 60 RIAs (Rich Internet Applications) ActionScript 3.0 and, 52 building with Flex, 5–10 creating with MXML, 4–5 Rich Internet Applications. See RIAs (Rich Internet Applications) RichTextEditor capabilities of, 93–94 overview of, 104 properties, 101–102 using behaviors, 131–133 RPC (Remote Procedure Call) request, 6. See also XML HTTP Service Requests RPM removal, of Flash plug-in, 38 RSLs (Runtime Shared Libraries), 17–19 RSS (Really Simple Syndication) feeds HTTPService RPC requests, 170–172 linking button to data, 175–178 linking DataGrid to data, 173–174 linking TextArea to data, 175 XML HTTP Service Requests and, 160 rssRequest object, 171, 173 Runtime Module, Apache/IIS, 24–25 runtime-referenced media assets embedded vs., 211 including images, 217–218 playing sounds, 216–217 runtime, resizing control at, 98 Runtime Shared Libraries (RSLs), 18–19

S sandbox, Flash Player, 20 Save and Launch dialog, 36 Saved Profile panel, 187–188 Scale Nine, 146 scale9Grid property, 141 SCP (Secure Copy Protocol), 224 SDK (Software Development Kit), Flex building applications, 23

downloading installation, 38–39 general requirements for, 37 installing, 39–41 running samples, 41–42 Secure Copy Protocol (SCP), 224 Secure Shell (SSH), 224 security, 19–20, 161–164 SelectionBeginIndex property, 102 selectionEndIndex property, 102 Separator menu item, 105 Server Configuration dialog, 32 service types, LiveCycle Data Services, 6 setSelection( ) method, 101 setter method, 74–75 SGML (Standard Generalized Markup Language), 50 SharedObjects, 20 Shockwave Component. See SWC (Shockwave Component) files Shockwave Flash. See SWF (Small Web Format or Shockwave Flash) files show( ) method, Menu control, 107 single quote ( ' ), 55–56 size ConstraintRows/ConstraintColu mns constraints, 143 controls, 97–98 Label control, 104 RichTextEditor control, 104 Skin Importer, 141–142 skins control, 99 graphical skinning, 154–157 modifying appearance, 141–142 overview of, 154 themes as collection of, 145–150 Skip All Breakpoints, 85 Small Web Format. See SWF (Small Web Format or Shockwave Flash) files Smoke theme, 147 snapshots Allocation Trace panel, 194–195 Loitering Objects panel, 191–193 Memory Snapshot panel, 190–191 Performance Snapshot panel, 196–197 Software Development Kit. See SDK (Software Development Kit), Flex sounds embedded, 213–216

features for, 10–11 overview of, 213 referenced, 216–217 source property, referenced images, 217–218 Sprite class, 97 SSH (Secure Shell), 224 Standard Generalized Markup Language (SGML), 50 states applying, 118–124 creating transitions between, 124–128 overview of, 116 and transitions, 117–118 States pane, Flex Builder, 118 static method, 73, 74 static variables, 69–70 strict data typing, 57 strict equality operator (= = =), 51 strings, 55, 241–242 styles for controls, 99 external CSS, 154 inline, 150 local style definition, 150–153 modifying appearance with, 141–142, 149–154 Property Inspector, 144–145 for skins, 155 for states, 123 text formatting, 101 themes as collection of, 145–150 super classes, 75 super prefix, 72 SWC (Shockwave Component) files creating binary file from, 17 deploying Flex applications, 18–19 as theme format, 146 SWF (Small Web Format or Shockwave Flash) files creating during compiling, 17–18 defined, 3 deployment and, 18–19 Flex limitations with, 12 generating with MXML, 5, 49 including media assets in, 210, 219–220 launching fdb debugger, 201–202 LiveCycle Data Services with Flex Builder and, 9 themes and, 146 Web integration, 19–20

273


274

Flex 3: A Beginner’s Guide

switch keyword, 62 switch statement, 51, 62 syntax, ActionScript, 52–53

effects and, 124–128 states and, 117–118 triggers, 116–117, 128–129

T

U

Tabbed browsing, and profiling, 182–186 testing, compiler module, 46 text-based controls Label control, 104–105 overview of, 93–94 properties, 100–101 for selecting and modifying text, 101–104 text property, 100, 102–104 TextArea control adding for data display, 167–169 linking to data, 175 overview of, 101–102 TextInput control, 101–103 TFP (Transfer File Protocol), 224 themes, 99, 145–150 this keyword, 72 Toggle Breakpoint, 85 Toggle Line Breakpoint, 85 Toggle Method Breakpoint, 85 tools, online resources, 248 toState property, transitions, 125 trace( ) function, 181, 206–207 Transfer File Protocol (TFP), 224 transitions defined, 116

UIComponent class, 97 Universal Resource Identifier (URI), 76 URI (Universal Resource Identifier), 76 url property, <mx:HttpService> tag, 170 URLRequest function, 175

V valid XML document, 50 values, functions returning, 60 var statement, ActionScript 1.0, 51 variables arrays as, 92–93 binding, 134–138 declaring, 54 instance, 70 modifying types, 56–57 naming, 54–55 overview of, 54 static, 69 types of, 55–56 Variables view, Flex Debugger, 86 VBox layout container, 167–168 video, 11, 219–220 View Source Browser view, 226–227 views Flex Debugger, 86

Flex Developer, 82–83 within Navigator container, 90 View Source Browser, 226–227 ViewStack navigator, 118 virtual machines, 52

W well-formed XML documents, 50 While loops, 63–64, 67 Windows default web root folder for, 223 installing Flex Builder in, 25–28 SSH clients, 224 using Apache/IIS Flex Module, 42–46 Wooden theme, 147 workspaces, 30 wrapper files, 19, 220–222

X XML (Extensible Markup Language), 50, 242–243 XML HTTP Service Requests, 164–178 accessing remote data with, 160 creating application, 166–170 getting data, 170–172 linking button to data, 175–178 linking DataGrid to data, 173–174 linking TextArea to data, 175 overview of, 164–165 XML object, menu control, 106–107

Profile for Arunkumar Ramachandran

Adobe Flex 3  

Adobe Flex Book

Adobe Flex 3  

Adobe Flex Book

Profile for anniyanvr
Advertisement