Adobe.Flex 3.0.For.Dummies

90 VISUALIZAÇÕES DOWNLOAD
Ferrari Red Power Masculino Baner Horizontal(728x90)
Cursos Online - Cursos 24 Horas
90 VISUALIZAÇÕES DOWNLOAD

spine=.864 Get going with Flex, and create RIAs in a Flash! Develop interactive applications without worrying about browser differences Flex lets you leverage the power of Adobe’s ubiquitous Flash technology to build large applications. If you’re eager to create Flex apps and you’ve written code in any language, this book will get you started, introduce you to Flex Builder and the Flex framework, and have you building some really flashy stuff before you know it! Doug McCune is a developer and Flex fanatic who has created several popular applications and Flex add-ons. Deepa Subramaniam is a computer scientist on the Flex Framework team.

Explanations in plain English “ et in, get out” infor ation Icons and other navigational aids Tear-out cheat sheet Top ten lists dash of hu or and fun Gm

Am ISBN 978-0-470-27792-8 $29.99 US $32.99 CN £15.99 UK Internet/Web Page Design Use the event model Work with ActionScript® and MXML Create, run, and debug a project Build simple user interface controls Set up data binding Explore styling and skinning

Companion Web site Go to www.dummies.com/ go/adobeflexfd Find code listings used in the book Use it to create your own cool RIAs liil r i rt I

® Doug McCune Deepa Subramaniam F ex you powe o create R ch nternet App cat ons

Adobe® Flex® 3.0 For Dummies® Published by 111 River Street Hoboken, NJ 07030-5774 www.wiley.com Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit- ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. Adobe and Flex are regis- tered trademarks of Adobe Systems Incorporated. All other trademarks are the property of their respec- tive owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITH- OUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FUR- THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR- MATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services, please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

About the Authors Doug McCune is a passionate Flex developer, consultant, and community contributor. He has been developing Flex applications since 2004 and is cur- rently a Principal Software Engineer at Universal Mind. Doug received a Bachelor of Arts degree in Science, Technology, and Society from Stanford University. Doug is active in the Flex open-source community and maintains a blog of his thoughts, code samples, and tutorials at www.dougmccune.com. He co-founded FlexLib, a leading resource for open-source Flex components created by community developers. Doug also enjoys speaking at Flex and Flash conferences — he has spoken at 360|Flex and Flash on the Beach.

Deepa Subramaniam is a Computer Scientist working on the Flex Framework team at Adobe. She joined Macromedia/Adobe in 2003, straight out of University of California, Berkeley where she received her Bachelor of Arts degree in Computer Science (Go Bears!). Deepa joined the early efforts that culminated in Flex 1.0 and has been working on Flex ever since. She might be described as one of the most enthusiastic Flex team members and is thrilled to be working with such bright engineers on such a cool product. Deepa is an active member of the Flex community, often speaking at large Flex and RIA con- ferences like Adobe MAX and 360|Flex. You can learn more about Deepa at her Web site, which includes her popular Flex blog, at www.iamdeepa.com.

Dedication We dedicate this book to Doc, for always keeping us on the clock and in good spirits.

Authors’ Acknowledgments We would like to thank Katie Feltman, Kim Darosett, and everyone else at Wiley who made this book happen. Thank you for believing in us and pushing us to the finish line. We also want to thank Darron Schall for his superb tech- nical editing of the book. And finally, we would like to thank everyone at Adobe, especially the Flex and Flex Builder teams, for encouraging us and offering technical support whenever we needed it. You guys are just awesome.

Doug’s Acknowledgments I would like to thank the loving and beautiful Jocelyn Sze — your patience and support during this process have been invaluable. You are my favorite. I also want to thank my father. As I write this, he is in the middle of the ocean sailing single-handedly across the Atlantic. Thank you, Dad, for never ceasing to inspire.

Deepa’s Acknowledgments This book would not have been possible without the love and encouragement of my amazing parents, S.N.P (Sam) and Amirtham Subramaniam, as well as my rocking sister, Suguna. They never waver with their loving support, and for this, I am ever thankful. Much love Amma, Appa, and Goons! A big thank you also goes to my extended group of friends who have listened to me chat- ter away about this book, Flex, and my life in general. Your friendship means so much to me.

Publisher’s Acknowledgments We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/.

Some of the people who helped bring this book to market include the following: Acquisitions and Editorial, and Media Development Project Editor: Kim Darosett Senior Acquisitions Editor: Katie Feltman Copy Editor: Becky Whitney Technical Editor: Darron Schall Editorial Manager: Leah Cameron Media Development Project Manager: Laura Moss-Hollister Media Development Assistant Project Manager: Jenny Swisher Media Development Assistant Producers: Angela Denny, Josh Frank, Shawn Patrick, and Kit Malone Editorial Assistant: Amanda Foxworth Sr. Editorial Assistant: Cherie Case Cartoons: Rich Tennant (www.the5thwave.com) Composition Services Project Coordinator: Erin Smith Layout and Graphics: Ana Carrillo, Nikki Gately, Laura Pence, Christin Swinford, Christine Williams Proofreaders: Melissa Bronnenberg, Christine Sabooni Indexer: Potomac Indexing, LLC

Introduction ………………………………………………………. 1

Part I: Introducing Flex ………………………………………… 7

Chapter 1: Getting to Know Flex ………………………………………………………………………….. 9

Chapter 2: Building Your First Flex Application …………………………………………………. 17

Chapter 3: Flexing Your Muscle with MXML and ActionScript……………………………. 27

Part II: Using Flex Builder (The Flex IDE)………………. 51

Chapter 4: Flex Builder: The Best Flex Development Tool ………………………………….. 53

Chapter 5: Introducing Flex Builder for Developers……………………………………………. 75

Chapter 6: Visually Designing Applications in Flex Builder ………………………………. 101

Charting Components ……………………………………….. 127

Chapter 7: Simple User Interface Controls ……………………………………………………….. 129

Chapter 8: Data-Aware User Interface Controls ………………………………………………… 157

Chapter 9: Forms, Formatters, and Validators …………………………………………………. 189

Chapter 10: Containers and Navigators ……………………………………………………………. 219

Chapter 11: Charting Components …………………………………………………………………… 253

Part IV: Working with Data in Flex ……………………… 283

Chapter 12: The Power of Data Binding ……………………………………………………………. 285

Chapter 13: Working with Data Collections………………………………………………………. 297

Chapter 14: Working with Remote Data ……………………………………………………………. 309

Part V: Exploring Advanced Flex Topics ………………… 321

Chapter 15: Working with Managers We Actually Love …………………………………….. 323

Chapter 16: Custom Components and Component Architecture………………………. 333

Chapter 17: Understanding States and Effects………………………………………………….. 347

Chapter 18: Styling and Skinning Flex Components ………………………………………….. 363

Part VI: The Part of Tens …………………………………… 381

Chapter 19: Ten Open-Source Flex Libraries…………………………………………………….. 383

Chapter 20: Ten Flex Resources……………………………………………………………………….. 391

Index ……………………………………………………………. 397

Introduction ……………………………………………………….. 1

About This Book …………………………………………………………………………………. 1

Foolish Assumptions …………………………………………………………………………… 2

Conventions Used in This Book…………………………………………………………… 2

How This Book Is Organized ……………………………………………………………….. 2

Part I: Introducing Flex ……………………………………………………………….. 3

Part II: Using Flex Builder (The Flex IDE) …………………………………….. 3

Part III: The Flex Framework and Charting Components……………… 3

Part IV: Working with Data in Flex ………………………………………………. 3

Part V: Exploring Advanced Flex Topics……………………………………… 3

Part VI: The Part of Tens …………………………………………………………….. 4

Companion Web site ………………………………………………………………….. 4

Icons Used in This Book ……………………………………………………………………… 4

Where to Go from Here ……………………………………………………………………….. 5

Part I: Introducing Flex…………………………………………. 7

Using Flex to Develop Rich Internet Applications ………………………………… 9

Understanding what an RIA is …………………………………………………….. 9

Taking a look at the rise of Flex ………………………………………………… 10

Defining Flex …………………………………………………………………………….. 10

What’s next? …………………………………………………………………………….. 12

Comparing Flex to Flash, AJAX, and Silverlight ………………………………….. 12

Flex versus Flash ………………………………………………………………………. 12

Flex versus AJAX ………………………………………………………………………. 13

Flex versus Silverlight ………………………………………………………………. 14

Taking Flex to the Desktop with AIR ………………………………………………….. 15

Creating a Flex Project in Flex Builder ……………………………………………….. 17

Writing Code for Your Project …………………………………………………………… 20

Deciphering the default code ……………………………………………………. 21

Creating the Hello World application………………………………………… 21

Viewing Your Application in Design Mode …………………………………………. 23

Running the Application ……………………………………………………………………. 25

Introducing MXML …………………………………………………………………………….. 28

Comparing MXML and HTML ……………………………………………………. 29

Nesting MXML containers…………………………………………………………. 29

Introducing ActionScript …………………………………………………………………… 30

Understanding objects and classes …………………………………………… 31

Defining getters and setters ……………………………………………………… 33

Learning to love the black box ………………………………………………….. 34

Recognizing that packages are where classes live …………………….. 35

Inheritance: Extending a class…………………………………………………… 36

Understanding interfaces………………………………………………………….. 37

Exploring static methods and variables ……………………………………. 38

Comparing ActionScript and JavaScript ……………………………………. 40

Working with the Event Model ………………………………………………………….. 42

Adding event listeners with MXML……………………………………………. 43

Examining the structure of an event listener …………………………….. 44

Adding event listeners with ActionScript ………………………………….. 45

Understanding event propagation …………………………………………….. 47

Listening for some common events ………………………………………….. 49

Part II: Using Flex Builder (The Flex IDE) ………………. 51

What’s Flex Builder, and Why Should I Care? …………………………………….. 53

Installing Flex Builder ……………………………………………………………….. 54

Taking a look at the Flex Builder perspectives ………………………….. 56

Customizing perspective views ………………………………………………… 58

Creating Different Types of Projects in Flex Builder…………………………… 59

Flex Projects …………………………………………………………………………….. 60

ActionScript Projects ……………………………………………………………….. 63

Flex Library Projects ………………………………………………………………… 65

Organizing and Editing Your Projects………………………………………………… 65

Editing existing project settings ……………………………………………….. 67

Deleting projects ………………………………………………………………………. 68

Software Development Kit (SDK) …………………………………………… 68

Importing and Exporting Existing Flex Builder Projects …………………….. 69

Importing a project …………………………………………………………………… 69

Exporting a project as an archive ……………………………………………… 70

Running and Releasing Your Projects………………………………………………… 71

Building and cleaning your projects …………………………………………. 71

Running your projects………………………………………………………………. 72

Releasing your projects ……………………………………………………………. 73

Accessing Flex Builder Help Materials……………………………………………….. 74

Anatomy of an MXML File………………………………………………………………….. 75

Including ActionScript with the tag……………………… 77

Introducing the tag ……………………………………………….. 78

Developer Tips and Tricks ………………………………………………………………… 79

Get the hint: Code hinting…………………………………………………………. 79

Going straight to the source code …………………………………………….. 81

Using automatic builds …………………………………………………………….. 82

Organizing import statements ………………………………………………….. 82

Squashing Bugs with the Visual Debugger …………………………………………. 84

Launching the debugging perspective ………………………………………. 84

Using breakpoints to step through code …………………………………… 84

Inspecting variables………………………………………………………………….. 86

Profiling Your Application …………………………………………………………………. 87

Taking out the garbage: The Garbage Collector ………………………… 87

Profiling memory use ……………………………………………………………….. 88

Profiling CPU performance ……………………………………………………….. 95

Refactoring Your Code………………………………………………………………………. 97

Changing class names ………………………………………………………………. 97

Changing method and variable names ………………………………………. 99

Living with limitations…………………………………………………………….. 100

Getting to Know Flex Builder Design Mode………………………………………. 101

Navigating Through the Design Area ……………………………………………….. 104

Using Pan & Zoom…………………………………………………………………… 104

Showing surrounding containers…………………………………………….. 105

Selecting Controls in the Design Area………………………………………………. 106

Controlling the Layout and Size of Controls in the Design Area ……….. 108

Positioning controls ……………………………………………………………….. 108

Snapping controls relative to each other ………………………………… 110

Aligning controls …………………………………………………………………….. 110

Sizing and resizing controls…………………………………………………….. 112

Inserting Components with the Components View…………………………… 113

Viewing the Contents of Your Application in Outline View ………………. 115

Working with States in States View ………………………………………………….. 116

Choosing a properties inspector view …………………………………….. 119

Using the properties inspector ……………………………………………….. 120

Setting constraints visually with the Constraints Control ……….. 121

Working with Style Sheets in CSS Design Mode………………………………… 123

Charting Components………………………………………… 127

Taking a Look at Simple Clickable Controls ……………………………………… 130

Creating button-based controls ………………………………………………. 130

Popping open controls with ComboBox and ColorPicker………… 139

Making dates: Using calendar controls in Flex…………………………. 140

Scrolling around ……………………………………………………………………… 143

Sliding around with Slider controls …………………………………………. 144

Introducing Text Controls ……………………………………………………………….. 145

Displaying text in Flex …………………………………………………………….. 145

Exploring text-input controls ………………………………………………….. 146

Working with HTML text …………………………………………………………. 149

Showing Off with the Flex Media Controls ……………………………………….. 149

Displaying images …………………………………………………………………… 149

Playing video ………………………………………………………………………….. 151

Playing audio ………………………………………………………………………….. 151

Showing progress with ProgressBar ……………………………………….. 153

Tying It Together: A Video Player Example ……………………………………… 154

Recognizing That Awareness Comes from the dataProvider ……………. 158

Creating Flash Data Objects in MXML and ActionScript …………………… 158

Array ………………………………………………………………………………………. 158

XML ………………………………………………………………………………………… 159

XMLList ………………………………………………………………………………….. 160

Creating Flex Data Objects in MXML and ActionScript …………………….. 160

ArrayCollection ………………………………………………………………………. 161

XMLListCollection…………………………………………………………………… 161

Powering Your Data-Aware Control with Data …………………………………. 162

Scrolling List Controls……………………………………………………………………… 163

Exploring the scrolling List controls ……………………………………….. 164

Making List controls display text…………………………………………….. 166

DataGrid Controls for Powerful Data Display …………………………………… 168

DataGrid …………………………………………………………………………………. 169

DataGridColumn……………………………………………………………………… 170

AdvancedDataGrid………………………………………………………………….. 171

Hierarchical Data Controls ………………………………………………………………. 173

Growing a Flex Tree ………………………………………………………………… 173

Navigating Flex applications with Menus and MenuBars …………. 174

Advanced Functionality in Data-Aware Controls ……………………………… 180

Scrolling in List, DataGrid, and hierarchical data controls ………. 180

and hierarchical data controls …………………………………………….. 181

Setting variable list row heights ……………………………………………… 182

Data-Aware Controls for Customizing the Display of Items ………………. 183

Drop-in renderer …………………………………………………………………….. 183

In-line item renderer ……………………………………………………………….. 184

with Multiple Inline Item Renderers ……………………………………………… 185

Delving into Form Layouts ………………………………………………………………. 190

Form: Recognizing the top dog ……………………………………………….. 191

FormHeading: Creating labels for different content areas ……….. 192

FormItem: Creating individual form elements …………………………. 193

Default Button: Helping out the end user ………………………………… 195

Validate Me……………………………………………………………………………………… 196

Customizing visual cues for validation errors …………………………. 196

Setting important properties on validators……………………………… 197

Triggering validation ………………………………………………………………. 200

Listening for validation events………………………………………………… 201

Checking out out-of-the-box Flex validators…………………………….. 203

Format Me……………………………………………………………………………………….. 209

Formatting data ………………………………………………………………………. 209

Handling formatting errors ……………………………………………………… 211

Tying It All Together: Creating an E-Commerce Form ………………………. 215

Introducing Basic Containers…………………………………………………………… 219

Understanding common container behavior …………………………… 220

Starting with a blank Canvas …………………………………………………… 223

Positioning items by using constraint-based layout ………………… 224

Managing your layout with box layout containers …………………… 225

Creating a tiled layout with the Tile container ………………………… 228

Using the Grid container …………………………………………………………. 229

Discovering Panel Containers and Control Bars ………………………………. 231

Panel ………………………………………………………………………………………. 231

TitleWindow …………………………………………………………………………… 233

Alert ……………………………………………………………………………………….. 235

Control bars……………………………………………………………………………. 237

Getting Up to Speed on Navigators ………………………………………………….. 239

Switching between views with the ViewStack………………………….. 239

Controlling a ViewStack with navigation bar controls……………… 240

Improving navigation with an Accordion ………………………………… 242

Creating tabs with the TabNavigator ………………………………………. 245

Optimizing performance with deferred instantiation ………………. 246

Tying It Together: Building a Form with Multiple Parts ……………………. 248

Filling Your Charts with Data …………………………………………………………… 254

Using the right series ……………………………………………………………… 254

Specifying the right fields ……………………………………………………….. 254

Creating a ColumnChart and BarChart …………………………………………….. 256

Clustering ……………………………………………………………………………….. 257

Stacking ………………………………………………………………………………….. 257

Designing a LineChart and AreaChart………………………………………………. 259

LineChart ……………………………………………………………………………….. 260

AreaChart ……………………………………………………………………………….. 261

Making a PieChart……………………………………………………………………………. 262

Going the simple route ……………………………………………………………. 263

Doing a donut shape……………………………………………………………….. 264

Exploding wedges …………………………………………………………………… 265

Building a PlotChart and a BubbleChart ………………………………………….. 267

Introducing the CandleStickChart and HLOCChart…………………………… 269

Working with Axes…………………………………………………………………………… 269

Adding Legends to Your Charts……………………………………………………….. 272

Adding Interactivity…………………………………………………………………………. 273

Animating Your Charts ……………………………………………………………………. 274

Tying It Together …………………………………………………………………………….. 276

Part IV: Working with Data in Flex ………………………. 283

Understanding the Data Binding Expression ……………………………………. 285

Using Data Binding in MXML……………………………………………………………. 286

in-line in MXML tags…………………………………………………………….. 286

MXML tag …………………………………………………….. 287

a data binding expression ……………………………………………………. 288

What Properties Support Data Binding?…………………………………………… 289

Moving Forward: Advanced Data Binding ………………………………………… 290

Binding to multiple destinations or sources ……………………………. 290

Constructing a bidirectional data binding expression……………… 292

Debugging Data Binding Expressions ………………………………………………. 292

Using Bindable Metadata …………………………………………………………………. 293

Why Use Flex Data Collections?……………………………………………………….. 297

Creating ArrayCollections ……………………………………………………………….. 298

Using MXML to create an ArrayCollection ………………………………. 298

Using ActionScript to create an ArrayCollection……………………… 299

Creating XMLListCollections……………………………………………………………. 300

Using MXML to create an XMLListCollection…………………………… 300

Using ActionScript to create an XMLListCollection …………………. 301

Common Collection Properties You Should Know …………………………… 302

Sorting and Filtering Collections ……………………………………………………… 303

Sorting Flex collections …………………………………………………………… 303

Filtering Flex collections …………………………………………………………. 305

Accessing Data Items ……………………………………………………………………… 306

Connecting with HTTP …………………………………………………………………….. 309

Loading your own XML file ……………………………………………………… 310

Asking for what you want ……………………………………………………….. 312

Loading someone else’s data ………………………………………………….. 313

Understanding the Flash security restrictions ………………………… 315

Connecting with Web Services ………………………………………………………… 316

Losing Weight with AMF Remoting ………………………………………………….. 320

Part V: Exploring Advanced Flex Topics …………………. 321

Dragging and Dropping with the DragManager ………………………………… 324

The FocusManager: Managing Which Controls Have Focus ……………… 325

Popping Up Dialog Boxes with the PopUpManager ………………………….. 327

Show Me the ToolTips: Using the ToolTipManager ………………………….. 330

SystemManager: The Engine Behind Your Application……………………..332

Looking at the Flex Component Life Cycle ……………………………………………333

Property invalidation: commitProperties………………………………… 334

Size invalidation: measure() ……………………………………………………. 336

Drawing and layout invalidation: updateDisplayList() …………….. 337

Creating Reusable Custom Components ………………………………………….. 337

Defining the interface ……………………………………………………………… 338

Choosing your base wisely ……………………………………………………… 338

Adding child components……………………………………………………….. 340

Choosing between MXML and ActionScript …………………………….. 341

Defining your properties …………………………………………………………. 342

Discovering how to talk with events ……………………………………….. 342

RatingSelector component…………………………………………………… 343

Using your shiny, new component ………………………………………….. 344

Working with View States ………………………………………………………………… 347

Creating view states with Design View ……………………………………. 348

States under the hood …………………………………………………………….. 352

Switching between states ……………………………………………………….. 352

Adding Effects to Your Application………………………………………………….. 354

Pulling the trigger …………………………………………………………………… 354

Starting with simple movement ………………………………………………. 355

Turning your world upside down ……………………………………………. 357

Zooming in and out…………………………………………………………………. 358

Wiping that look off your face …………………………………………………. 359

Running multiple effects …………………………………………………………. 360

Combining States and Effects by Using Transitions …………………………. 362

Styling……………………………………………………………………………………………… 364

Applying styles with MXML …………………………………………………….. 364

Using the block ……………………………………………………… 365

Attaching an external style sheet ……………………………………………. 368

Changing styles with ActionScript…………………………………………… 368

Working with fonts …………………………………………………………………. 370

Understanding the limitations of styling …………………………………. 372

Skinning…………………………………………………………………………………………… 372

Using graphical skins………………………………………………………………. 373

Simple example: Skinning a Button control……………………………… 373

Extended example: Skinning a Panel container ……………………….. 376

Part VI: The Part of Tens……………………………………. 381

Index …………………………………………………………….. 397

Introduction T here has never been a better time to be a software developer. Web-based applications have come a long way since the early 1990s. You can now create applications that provide amazingly rich experiences, all of which can be delivered through a simple Web browser to any computer in the world. Rich Internet Applications (RIAs) aren’t just a passing fad; they signal the emergence of a new breed of powerful, immersive applications that will lead the evolution of the Web.

Flex is on the forefront of this movement. And, the fact that you took the first step by picking up this book means that you’re part of this exciting time. RIA developers are making applications that people didn’t think were possible. With Flex, you can create full enterprise-scale Web applications that have as much interactivity as the best desktop applications. Flex enables some excit- ing possibilities. We hope that this book exposes this powerful technology to a much wider audience and lowers the barrier for new developers.

Flex lets you leverage the power of the Adobe Flash technology to make large applications. And, because Flash is deployed on nearly all Internet-connected computers, you’re developing for a near-ubiquitous platform without ever having to worry about browser differences and incompatibilities. The move to Flex from other Web technologies means that you can focus on creating impressive applications rather than debug in three different browsers. And, because Flex is based on Flash, you can instantly add video and other rich media to your applications.

So, if you’re ready to step up your game and start making the next generation of Web applications, crack open this book and get started. Welcome to Flex!

About This Book Most books about Flex are massive and assume that the reader has been programming since age 12. Adobe Flex 3.0 For Dummies, on the other hand, has been written specifically for the beginning Flex developer. If you have heard about Flex, but aren’t quite sure what all the buzz is about, this book is for you. We hope that our enthusiasm is contagious because we truly believe that Flex is the most exciting program a software developer can use.

Foolish Assumptions Adobe Flex 3.0 For Dummies is an introductory book, so we don’t assume that you already know how to use Flex, although we hope that you know enough about it to realize that it’s something you want to use. Part I of this book covers some general programming concepts that you need for develop- ing Flex applications; however, we don’t cover the most basic programming topics. If you have experience in writing code in another language, such JavaScript, Java, or C++, you shouldn’t have any trouble because we intro- duce ActionScript (which is the language you use for Flex). We do assume that you’ve written code in another programming language. If you come from a background in using Flash and ActionScript 2, be sure to brush up on the first few chapters to make the transition to ActionScript 3. (After you do, you’ll never go back.) We also assume that you have a cursory understanding of HTML. Although Flex doesn’t use HTML, some of the markup language used in Flex applica- tions is similar to HTML, and we draw analogies between the two.

Conventions Used in This Book When we mention new terms, we write them in italics, followed by explana- tions of the terms. Also, we include a lot of sample code in this book because we figure that one of the best ways to find out how to write code is to see it. The code in this book appears in a special font, as shown here:

text=”Hello World” How This Book Is Organized Adobe Flex 3.0 For Dummies is organized into six main parts, which contain a total of 20 chapters. Don’t feel that you need to read these parts in sequential order; you can jump around as much as you like, and each part is meant to stand on its own. The beginning of the book introduces Flex and some gen- eral programming concepts that are useful if you haven’t done much object- oriented programming. Depending on your background, you may want to start by jumping straight to the meat of the Flex framework in Part III, or start at the beginning with an overview of ActionScript and MXML in Part I. Part V is the only part that covers more advanced topics and probably requires that you read some of the earlier content before tackling it.

Introduction 3 Part I: Introducing Flex In Part I, we introduce Flex and the technology that you use to create jaw- dropping RIAs. Chapter 1 describes the evolution of Web technologies and how Flex stacks up against some competing technologies. Without overload- ing you with complex details, we help you jump right into building your first Flex application in Chapter 2. Then, in Chapter 3, we back up a bit and explain some important object-oriented programming principles.

Part II: Using Flex Builder (The Flex IDE) Part II is all about the tool you use to create Flex applications: Flex Builder. Chapter 4 gives you an overview of Flex Builder, and then we divide the content to highlight developer-focused features (Chapter 5) and designer- focused features (Chapter 6).

Part III: The Flex Framework and Charting Components Flex contains a large and powerful toolset of components that you use to create applications. In Part III, we dive head first into the Flex framework and show examples of using all the different components. The chapters in this part are fairly self-contained, although later chapters might reference compo- nents that we cover earlier. Each chapter covers a set of related components, and at the end of each chapter, a larger example ties together all the compo- nents covered in the chapter.

Part IV: Working with Data in Flex Flex applications are only as good as the data that drives them. Chapter 12 covers data binding, which is one key piece that makes Flex development so powerful. Chapter 13 dives into data collections, and Chapter 14 explains how to pull data from other sources on the Web.

architecture and touches on custom component development. Chapters 17 and 18 cover elements that give your applications a bit more kick, such as transitions, skins, and styling.

Part VI: The Part of Tens The Part of Tens consists of a few fun lists that let you continue finding out about Flex after you finish this book. Chapter 19 has a list of ten open-source projects that you can freely use in any of your Flex projects. (Haven’t you been dying to play with a 3D engine?) Chapter 20 lists ten resources that are essential bookmarks for all Flex developers.

Companion Web site We write quite a bit of code in this book, but don’t worry: You don’t have to retype it all by hand. Most of the code that you see here is provided on this book’s companion Web site:

www.dummies.com/go/adobeflexfd You can download the code and then copy and paste it directly into your Flex projects.

Additionally, a bonus chapter titled “Optimizing Your Flex Applications” is available for downloading from the companion Web site. This chapter gives you some optimization tips to help streamline your Flex application’s performance.

Icons Used in This Book As you’re reading, you’ll notice a few funny-looking icons on the edge of the page. Here’s what each of these icons means: The Tip icon points out some information that we think is especially impor- tant or interesting. It’s often something that might not be obvious but that saves you time and makes Flex development even easier.

This icon marks certain nuggets of information that we think are extra impor- tant to remember. This information is good to drill into your head because we’re sure that it will come up repeatedly in your Flex development.

Introduction 5 Sometimes we throw in some extra details that aren’t essential but can give you a broader understanding of what’s going on behind the scenes. This infor- mation often includes details about the inner workings of Flex.

We all make mistakes, and we use this icon to warn you of potential mistakes (ones we’ve already made!).

Where to Go from Here If you’re brand-new to Flex, the first few chapters provide an overview of the core concepts that become important building blocks. If you already have experience in programming (with ActionScript or a language such as JavaScript), you can probably jump past a chapter or two in Part I. Every chapter in Adobe Flex 3.0 For Dummies is meant to stand on its own, so feel free to jump around as you like and find information in the order that inter- ests you the most.

W e agree with you: Flex can be overwhelming in the beginning. Part I eases you into the world of Flex by introducing the core concepts and providing a bit of context so that you understand how Flex fits in with other, related technologies. Chapter 1 talks about the evolution of Flex and compares Flex with other software products — and then explains why Flex comes out on top, of course! After getting to know Flex a bit, you jump right in with Chapter 2 and start building an application. Then in Chapter 3, we back up and explain some of the key pro- gramming concepts that you use in Flex development. If you’re already familiar with Flex or object-oriented pro- gramming (OOP), you can probably jump straight to Part II. But if you haven’t been exposed to OOP principles, take a little time to review these chapters.

Chapter 1 Getting to Know Flex In This Chapter Understanding what Rich Internet Applications (RIAs) are Comparing Flex to other RIA technologies: Flash, AJAX, and Silverlight Taking Flex applications offline by using Adobe Integrated Runtime (AIR) A dobe Flex is an application development platform that you can use to build Rich Internet Applications (RIAs). Flex applications are Web-based, but they provide immersive levels of interactivity and rich media experiences that make them seem more like computer desktop programs than traditional Web applications. Flex is the ideal technology to use when you want to create complex data visualization, performance dashboards, multimedia experiences, and countless other interactive applications. RIAs are raising the bar for Web applications, and Flex is leading the way. In this chapter, we discuss what Flex is, what it isn’t, and how it compares to other technologies.

Using Flex to Develop Rich Internet Applications The computer world has come a long way from static HyperText Markup Language (HTML) Web pages. Over the past two decades, rich online experi- ences have gradually evolved into RIAs. Flex is on the forefront of technology that allows you to create such engaging Web-based applications, but it has taken nearly 20 years since the first HTML page was created to get to where we are now. (See the nearby sidebar for more on the journey from HTML to RIA.)

load data within the application. Simple HTML Web pages require a full page refresh to load new data. RIAs, on the other hand, load data asynchronously, which means they can load chunks of data without requiring page refreshes and they keep track of the application state in memory. Flex applications are stateful clients, which means they store data about the current state of the application, such as the content of a shopping cart, in memory in the client.

Asynchronously loading XML is an integral part of all RIA technologies (not only Flex). Version 4 of Flash, which was released in 1999, was the first version of Flash that let developers load external XML data into Flash applications.

Taking a look at the rise of Flex Macromedia, which Adobe later acquired, introduced the first version of Flex in March of 2004. Initially, the first two major releases, Flex 1 and 1.5, were expensive server-based products. A license for Flex 1.5 cost about $15,000, and you had to deploy a server application that would compile your Flex applications and serve them to the user. These initial versions of Flex were based on Flash Player 7 and ActionScript 2, and the code editor was based on the Macromedia Dreamweaver editor.

The release of Flex 2 marked a dramatic shift in the product line. Flex 2 was no longer a server technology at all; instead, Flex was a completely client- side product. The cost dropped dramatically, and Adobe rewrote the entire Flex framework and the Integrated Development Environment (IDE) from the ground up. Flex 2 was based on Flash Player 9 and ActionScript 3, which brought serious performance gains.

Flex 3 added additional functionality to Flex Builder, such as refactoring and enhanced styling support, as well as new data visualization components in the Flex framework. Flex 3 also marked the official open-source release of the Flex SDK and Flex compiler. For more on the open-source aspect of Flex, visit http://opensource.adobe.com.

Defining Flex Defining exactly what Flex is can be confusing because Flex actually includes a combination of different technologies. Flex is not a single software product, but instead includes the following four main pieces: Languages: ActionScript 3 and MXML You use a combination of ActionScript, a scripting language, and MXML, a markup language, to create Flex applications. MXML is similar to HTML, so if you have experience creating HTML Web pages, then you should be able to figure out MXML pretty easily.

Chapter 1: Getting to Know Flex 11 Component framework: Flex SDK The Flex SDK (also known as the Flex framework) is a set of user inter- face components, such as lists, buttons, and charts, that you use to build Flex applications. The Flex SDK (with the exception of the charting package) is free and open source.

Integrated Development Environment (IDE): Flex Builder You use Flex Builder to edit your code, compile your applications, debug your code, and profile performance. Flex Builder is an integrated devel- opment environment (IDE) sold by Adobe.

Cross-browser runtime: Flash Player You deploy Flex applications in a Web browser with the Flash Player plug-in. You can also deploy Flex applications as standalone desktop applications by using the Adobe Integrated Runtime (AIR).

From HTML to RIA When programmers began tinkering with the Web, they used HTML to create Web pages that looked like actual pages of a book. These pages contained a bunch of text that someone wrote and published for the world to read. Those were the good old days of choppy animated images and heavy use of the tag, which was about as “rich” as the Internet got in the early ’90s. Then, Web servers became more sophisticated and started serving up dynamic content, depending on what users were looking for or how they inter- acted with the Web site. For the first time, Web pages started turning into Web applications.

Server-side languages, such as Java, PHP, and ColdFusion, increased the capabilities of Web applications on the back-end. An e-commerce site could let you keep track of items in your shopping cart while you browsed the retailer’s site, but each time you added an item, the full Web page would have to reload so that the number of items shown in your cart would stay updated. The state of the application was stored completely on the server, either in memory or in a database. Whenever the server wanted to show you something new, you were sent to a new static HTML page.

But then those static Web pages became ani- mated when a small company called FutureWave Software released FutureSplash Animator, which was purchased by Macromedia and renamed to Flash in 1996. A whole new breed of silly animated movies and impressive visual effects appeared. The Flash platform brought a greater level of interactivity to the Web than ever before. Designers could create interactive visual experiences that went far beyond what was possible with simple HTML.

Flash 5 included the ActionScript program- ming language, which turned Flash into much more than a simple animation tool. Developers started creating complex Flash interactive experiences by combining the visual and pro- gramming capabilities to produce full-blown applications within a Web browser. The first RIAs were being created before the term RIA was widely used or understood. Then in 2004 Finally developers had a tool that was specifi- cally for creating RIAs.

Adobe is actively developing Flex 4, codenamed Gumbo. This version will focus on an improved workflow between developers and designers, and will likely include an improved component framework model to more gracefully separate the visual design of your Flex applications from the underlying code. Toward a similar goal, an additional product in the Flex product line (code-named Thermo) will focus specifically on allowing designers to create complex RIA user interfaces and interactions by using a visual editor, which will create Flex application code that the designer and developer can share.

Flex has been largely in a class of its own when it comes to RIA development platforms, but that reign is now being challenged because some serious competitors are entering the RIA market. Microsoft’s Silverlight platform and Sun’s JavaFX are two RIA development products aimed directly at taking on Flex. Over the next few years, the competition will get serious, which can only be a good thing for all the developers out there. RIA development is an exciting field; you’ve chosen wisely!

Comparing Flex to Flash, AJAX, and Silverlight Because you bought this book, we assume you’ve decided that Flex is the right choice for your project. But, if you need to sell the decision to your boss, he or she will probably ask you how Flex compares to related technolo- gies. The following sections summarize some of the key differences between Flex and a few other RIA technologies.

Flex versus Flash Whenever Doug tries to explain what he does for a living, someone always asks whether Flex is Flash. This question quickly leads to a heated discussion about Flash advertisements, and he has to calm everyone down and explain that, fundamentally, Flex is a Flash-based technology, but no, he doesn’t make those annoying ads — he makes applications. Flex is an application development framework and toolset that you can use to create RIAs. These applications are delivered over the Internet by using the Flash Player.

Chapter 1: Getting to Know Flex 13 The Flex framework: Flash has its own component set that has some of the same functionality as the Flex SDK, but it does not provide as many components and does not include charting components, layout contain- ers, and other framework features that are very useful for developing large applications.

MXML: You can use MXML markup to create your Flex applications, but this markup language is not available in Flash. Flash does use the same ActionScript 3 scripting language, however.

A powerful Integrated Development Environment (IDE): Flex Builder was designed specifically to build applications, as opposed to the Flash You can use both tools to create RIAs, but Flex Builder has features like code-hinting, a powerful debugger, and a profiler that make it a more powerful development tool.

You can use Flash, rather than Flex, to create RIAs, but you have to work in the Flash Authoring environment, which means you don’t get the benefits of Flex Builder (such as code hinting), and you can’t use the MXML markup language. You may find the Flash Authoring tool really helpful if you’re creat- ing animated movies. It uses the timeline metaphor when you create anima- tions and includes drawing tools. Flex Builder, on the other hand, is designed for application development, not animation creation. Flex Builder doesn’t include any drawing tools, and it has no timeline.

If you have to decide between Flex and Flash for a specific project, think about exactly what kind of project you’re working on. Flex excels when you’re creat- ing large desktop-like applications, sharing work among a team of developers, or visualizing data with charts and graphs. For other kinds of projects that require complete control over the visual experience, such as games or adver- tisements, Flash might be a more appropriate choice.

Flex versus AJAX Asynchronous JavaScript and XML (AJAX) is a technique that you can use to load data into HTML Web pages without refreshing the full page. Instead of sending a new HTML page to the user’s Web browser for every change, AJAX applications send XML asynchronously and update relevant portions of the screen when needed. By using AJAX, you often end up with a much more responsive user interface and a more desktop-like application experience. Flex applications also asynchronously load XML data.

is currently developing Edition 4. JavaScript is currently an implementa- tion of ECMAScript Edition 3. The current version of JavaScript most closely Adobe released ActionScript 3 in 2006, which is based on the preliminary draft of ECMAScript Edition 4. After Ecma officially releases a new version of ECMAScript Edition 4 and Web browsers support an updated version of JavaScript, the JavaScript programming language should become more like ActionScript 3.

Because of the similarities between the ActionScript and JavaScript lan- guages, and their similar approaches to asynchronously loading XML data, the fundamental benefits of Flex have to do with its underlying Flash Player technology. Here’s a rundown of some of those benefits: Multimedia capabilities: Flash Player allows you to create a whole range of rich multimedia experiences that you simply can’t achieve by using HTML and JavaScript. Flash has powerful graphics capabilities that can do complex drawing and image manipulation. In addition, Flash supports audio and video streaming, so many leading online video sites use it to play video on the Web.

Cross-browser support: You can be sure that any Flex application you develop will look and behave the same way in all browsers on all plat- forms. Web browsers all have their own quirks and idiosyncrasies when When you develop AJAX applications, you need to test your application in multiple Web browsers to make sure your application is compatible with them all. However, because Flex applications rely on the Flash Player, you can be assured that your application will look the same, pixel for pixel, and behave the same across all browsers.

Flex versus Silverlight Microsoft’s competitive RIA technology is Silverlight, a browser plug-in, like Adobe’s Flash Player. Just like you have to install the Flash Player plug-in to run Flex applications, you need the Silverlight plug-in to run Silverlight appli- cations. Because Silverlight is fairly new, the Silverlight plug-in isn’t nearly as common as Flash Player. Silverlight will likely become more widely used in the future, but right now, the Flash Player plug-in has a strong advantage because of the large number of computers on which it is installed.

The first release of Silverlight 1.0 included the browser plug-in and focused on streaming video on the Web. This release certainly competed with Flash Player because it focused on some of the media features of Flash, but it didn’t really threaten Flex’s position because Silverlight 1.0 didn’t contain a set of user interface controls that you could use to build RIAs. Silverlight 1.0 pro- vided all the low-level graphics capabilities but none of the application frame- work pieces.

Chapter 1: Getting to Know Flex 15 In early 2008, Microsoft released the first beta version of Silverlight 2.0 (origi- nally named Silverlight 1.1), which included a set of UI controls, such as a DataGrid, CheckBox, and Slider. These new controls make Silverlight a closer competitor with Flex. The competition between Flex and Silverlight has just begun, and it’s too early to draw any firm conclusions about how serious a competitor Silverlight will become.

Taking Flex to the Desktop with AIR Adobe developed Adobe Integrated Runtime (AIR), previously code-named Apollo, to let you deploy Flex applications as computer desktop applications. By using AIR, you can create your own desktop applications that can run natively on Windows, Mac, and Linux operating systems. You can create AIR applications as Flex applications or AJAX applications, so if you know how to create Flex or AJAX applications, you can create desktop applications, too.

When deciding whether AIR is the right technology for your application, con- sider these three main features that AIR provides: Local file-system access: One of the main reasons for moving from a Web-based Flex application to a desktop AIR application is the inte- grated local file-system access that AIR offers. If you build a Flex-based AIR application, you get a few extra tools that don’t come in the normal Flex framework. These tools let you read and write to the user’s local file system.

Integrated Web browser: The AIR runtime includes a built-in Web browser: the open-source WebKit browser. This Web browser allows you to load full HTML pages right into your application, something that you can’t do in a Web-based Flex application. The AIR framework also lets you display PDF files within your application.

Embedded SQLite database: AIR applications can access an embedded database for offline database access. So, you can build applications that can connect to a server database (like a typical Flex application can) or to an offline database if your application is only occasionally connected to the Internet.

Using the AIR-specific framework controls falls outside the scope of this book. If you’re interested in finding out more about AIR, visit www.adobe. com/products/air.

Chapter 2 Building Your First Flex Application In This Chapter Writing your first Flex application Running your application in a browser Editing your code in Source mode Viewing your application in Design mode I n an homage to software examples all over the world, in this chapter you use Flex Builder to write your first Flex application, the classic Hello World, which displays the words Hello World on the screen. While writing this application, you find out how to choose Flex user interface controls, construct an application in the Flex Builder tool, and launch and run the application so that it can be viewed in a browser window.

The focus of this chapter is to show you how to create a quick-and-dirty appli- cation so that you can see how the development tool and framework elements work together. The rest of this book describes Flex Builder (the Flex develop- ment tool) and the Flex framework in more detail. In later chapters, you find out more about how to construct and debug a Flex application, how to deter- mine which elements are available when building your Flex applications, and how to wire them together.

Creating a Flex Project in Flex Builder To write your Hello World Flex application, you use the best tool for writing, debugging, and running Flex applications: Flex Builder. You can use this inte- grated development environment to do the following: Write Flex applications with MXML and ActionScript code.

Visually assemble Flex applications by placing controls on a visual design stage.

Build and run your Flex application in a browser window or as a desktop application.

If you don’t have Flex Builder already installed, you can download the free trial version from www.adobe.com/go/flex/. The trial version lets you build full Flex applications for 60 days before deciding if you want to purchase the prod- uct. Refer to Chapter 4 for more detailed instructions on downloading Flex Builder and a description of the different versions of Flex Builder.

To write the Hello World Flex application, you must first create a new project in Flex Builder. Follow these steps: 1. Open Flex Builder.

The first time you launch Flex Builder, the Flex start page opens, as shown in Figure 2-1. This page has all sorts of handy links and informa- tion to help get you started building Flex applications. To get up to speed quickly, check out the tutorials that are linked from the Flex start page.

Figure 2-1: The Flex Builder start page provides many handy tutorials and tips.

Chapter 2: Building Your First Flex Application 19 The New Project Wizard for creating Flex project types appears, as shown in Figure 2-2. The wizard walks you through the steps of creating the project.

Flex Builder organizes its Flex content within projects. You can create several different kinds of projects, depending on what kind of application you want to build. (To find out more about the different kinds of projects available and how to create them in Flex Builder, refer to Chapter 4.) The most common and basic project type is a Flex project. You create this type of project to house your Hello World Flex application. After you’ve created a project, the other Flex Builder features — such as the code editor, visual debugger, and visual Design mode — are available for you to use.

Figure 2-2: The Flex Builder New Project Wizard walks you through creating a Flex project.

3. Enter a project name (for the sample application, enter Hello World) and click Finish.

all projects that exist in your workspace. A workspace is a location that houses all your projects.

A status bar appears at the bottom of the New Project Wizard, indicating that Flex Builder is creating all the necessary files on the file system to house your Hello World project. After the project is created, you see it in Navigator view on the left. A set of folders is created, and the root Flex application for that project opens in Source mode, as shown in Figure 2-3. By default, Flex Builder names the root application for a project main.mxml.

Source mode Design mode Navigator View Figure 2-3: Your new Flex project appears in Navigator view, which lists all proj- ects in the workspace.

Writing Code for Your Project When you create your Flex project, you can start writing code. A simple Flex application, main.mxml, is also created, and Flex Builder opens the MXML application in Source mode (refer to Figure 2-3). This Flex Builder mode offers all the developer-related tools, such as code editors, the debugger, and refac- toring options.

Chapter 2: Building Your First Flex Application 21 Deciphering the default code After you create a project, Flex Builder writes the following chunk of code into main.mxml, by default:

The code breaks down as follows: XML declaration: An XML declaration tag appears at the top of the application, identifying the document as an XML document.

Application MXML tag: Below the XML declaration is the Application MXML tag, which is the root tag of any Flex application. The Application tag has some important jobs, such as expressing the namespace of the controls used in the application. By default, Flex Builder autogenerates code that fills in the mx namespace (xmlns:mx=”http://www.adobe.com/2006/mxml”), which is the namespace where the Flex controls and containers live. You can see this namespace declaration directly in the Application tag.

Attribute declaration: Following the namespace declaration on the Application tag is an attribute declaration. The layout attribute determines which type of visual layout the Application control invokes when positioning its children. By default, Flex Builder sets the layout property to the value absolute, which means that the child elements of the Application control are all positioned at explicit x and y locations within the document.

Closing Application tag: Because all XML tags must be closed, Flex Builder adds the closing tag to make the docu- ment valid.

Creating the Hello World application You know that you want to create a Flex application that simply displays Hello World when it’s run. The Flex framework has a variety of user interface controls that can be used to display information in a Flex application. (To find out more about all the available Flex user interface controls, refer to Part III of this book.) One simpler control that you can use is the Flex Label control. This display-only text control writes text to the screen. You can create a Flex Label control by using the MXML tag. The contents of the Label control (the text that it chooses to display) is set in the text attribute to a value that is a String object.

Follow these steps to use the Label control to display Hello World in your application: 1. Write an tag directly in the MXML code editor, which opens by default when you create a new Flex project.

Flex Builder’s code hinting feature uses built-in intelligent heuristics to suggest different tags and attributes based on the characters you’re typing. As you start typing an opening tag, <, Flex Builder makes com- ponent suggestions in a drop-down list. As you continue typing the mx: namespace prefix and the first letter of Label, L, Flex Builder narrows its suggestions to match the characters you type. After you type the L, Flex Builder suggests the Label component, as shown in Figure 2-4. You can press Enter to autofill the Flex Builder suggestion, or you can finish typing on your own.

Now that you have created a Label control in your Flex application, you need to tell it to display the words Hello World. This task is simple — a Label control uses the text attribute to specify the text it should display.

Figure 2-4: The code hinting drop-down list gives you sugges- tions as you enter code in the code editor.

2. Directly in the Label MXML tag, add the following code: text=”Hello World!” You may have noticed, as you add the text attribute to the Label tag, that Flex Builder suggests other attributes that can be set on a Flex Label control. Flex Builder provides not only tag-level code hinting but also attribute code hinting.

Chapter 2: Building Your First Flex Application 23 based on their x and y properties. Because the Label control hasn’t specified an explicit x, y position, the Application container places the Label control at its default position: 0,0. This position indicates that the Label control lives at the upper-left corner of the screen.

If you center the Label control within your application, you can create a more visually pleasing effect. You can easily use the built-in layout con- straints, where user interface controls are constrained to the edges of their parent container. (To find out more about layout constraints, refer to Chapter 10.) 3. To center the Label control, add one center constraint to the Label tag Add this code to the Label MXML tag: horizontalCenter=”0” The horizontalCenter constraint is set to a pixel value that determines the distance between the center of the control and the center of its parent container. Setting the Label’s horizontalCenter attribute to a value of 0 perfectly centers the control in the center of the application.

When you’re finished, your code should look like this (see Figure 2-5):

Figure 2-5: The finished code for your Hello World Flex application.

tab in the upper-left toolbar in Source mode (refer to Figure 2-3). (To find out more about Flex Builder Design mode and how to author and modify Flex applications and components visually, refer to Chapter 6.) When you click the Design tab, Flex Builder changes to Design mode, shown in Figure 2-6. This view has a design stage that shows how the application’s current state appears. Additionally, you can use the panels flanking the design stage to drag new Flex components to add to the design and to edit existing components. Whenever anything is done in Design mode that changes the state of the application (for example, dragging out a new component or changing a component property), the corresponding code is added or modified in Source mode. Everything done in Design mode results in generating or modifying the correct code in Source mode. Similarly, every change you make in Source mode gets represented in Design mode.

In Figure 2-6, you can see that the design stage shows a Flex Label component centered in the Application container. That’s how your Hello World appli- cation will look in the browser when you run it.

Run button Design stage Figure 2-6: Design mode ren- ders an application to indicate what it will look like when you run it.

Chapter 2: Building Your First Flex Application 25 Running the Application Flex Builder is a one-stop tool for all your Flex development needs. Within Flex Builder, you can write, run, and debug applications. Before you can run a Flex project, however, you need to build it. Building a project means that you invoke a compiler — in this case, the Flex MXML compiler — to compile code and check for errors. If errors exist, you need to fix them and then build the project again. After the project is successfully built, you can run it and view your Flex application in a browser window.

When you launch a Flex application, you’re building the application, check- ing for errors, and then running the application in a browser window. Flex Builder offers a variety of toolbars that have buttons for invoking different actions, such as running, debugging, or profiling an application. To launch your Hello World project, click the Run button on the main code toolbar (refer to Figure 2-6), which is available in either Source mode or Design mode. Flex then builds the application and launches it in a browser window. By default, Flex Builder launches the application in your computer’s default Web browser.

If problems exist in your application code, you see them written out to Problems view, at the bottom of the code editor window. If no errors exist, your application is launched in the default browser window, and you should see your application running! The result of the Hello World program looks like Figure 2-7.

There you go. In just a few, simple steps, you built a simple Flex applica- tion in Source mode, viewed it in Design mode, and ran the application in a browser window.

Figure 2-7: Running the application launches a browser window showing the finished product.

Chapter 3 Flexing Your Muscle with MXML and ActionScript In This Chapter Understanding MXML and ActionScript Developing object-oriented applications Using inheritance and interfaces Working with the event model F lex applications are created by using a combination of the declarative markup language MXML and the scripting language ActionScript. You use both MXML and ActionScript, often together, to create your projects. If you’re familiar with developing AJAX Web applications, try drawing an analogy between HTML and JavaScript. When you create AJAX applications, you use HTML as the declarative markup language to lay out the user interface elements of your appli- cation, and then you use JavaScript to add interactivity. MXML and ActionScript work much the same way, with MXML often serving to create the visual layout of your application and ActionScript adding powerful programming capabilities.

In this chapter, we provide an overview of MXML and ActionScript and explain the power and unique capabilities of each technology. To become a successful Flex developer, you should grasp some important general programming concepts, so we cover some object-oriented programming principles and discuss the event model that’s used for communication among the different pieces of your application.

In this chapter, we make some assumptions about your programming knowledge. We assume that you have some experience in writing code in a programming language such as JavaScript, Java, C, C++, or Basic and that you have at least a cursory understanding of HTML or XML. Although you certainly don’t need to be an expert programmer in any specific language, we don’t cover all the small details of fundamental programming concepts. If tasks such as working with for loops, declaring variables, and invoking functions are foreign to you, you may need to spend some time reading about these fundamental concepts because a discussion of that information is outside the scope of this book.

Introducing MXML MXML is a tag-based declarative markup language that you use to compose Flex applications. When you start a new Flex project, you begin with a new MXML file. As we explain in Chapter 2, every Flex application starts out as an MXML file with an empty tag. MXML is contained in files that use the .mxml extension.

You create components by creating new MXML tags. The following tag creates a new Button component and sets the label that’s displayed on the Button:

By adding that single line to your main application MXML file you have added an interactive Button. The Flex framework contains a number of different user interface controls that you can use in your applications, with the Button being one of the simplest ones. All the Flex framework controls can be added with MXML. Listing 3-1 creates a simple login form, shown in Figure 3-1.

Listing 3-1: A Simple Login Form

Chapter 3: Flexing Your Muscle with MXML and ActionScript 29

For now, don’t worry about exactly what the Form or TextInput controls can do; we cover all the controls in later chapters. (We discuss Forms in Chapter 9 and text controls, such as TextInput, in Chapter 7). Notice how the MXML components are defined in Listing 3-1, however, because you use this general syntax throughout your Flex development.

Comparing MXML and HTML If you’re familiar with HTML, MXML probably doesn’t look much different. But don’t let the similarity of the syntax fool you; MXML is completely dif- ferent from HTML. None of the normal HTML user interface components are present. There are some similar components, however, such as TextInput (which can be created with the MXML tag). TextInput is similar to the HTML tag. But even though some of the MXML tags might resemble HTML components, be aware that they are, in fact, different controls.

Nesting MXML containers The Flex containers are a subset of the components in the Flex framework that are specifically designed to hold other controls. A few of the containers that you use in your applications are Canvas, HBox, VBox, and Panel. You can define these containers in MXML and add child components by nesting MXML tags. The following example creates a horizontal box container that holds two Button controls (shown at the top of Figure 3-2):

Because the two tags are placed between the opening HBox tag () and the closing HBox tag (), they are added to the HBox, which lays them out horizontally. You can nest MXML tags within each other multiple levels deep, to produce complex layouts. The following code creates a Panel container that contains an HBox, which contains the two Buttons (as shown at the bottom of Figure 3-2):

Figure 3-2: Using nested containers to lay out Flex Notice how the opening and closing tags for the Panel and the HBox have to completely surround their contents. Make sure that you always properly nest your MXML tags, or else your code doesn’t compile. The following is an incorrect example of nesting that generates an error:

If you tried to run the above code the compiler would tell you that you haven’t properly closed the HBox tag.

Introducing ActionScript MXML can be great for creating layouts of user interface controls for your applications, but when you need more programmatic control, you use ActionScript. The syntax of ActionScript is close to that of JavaScript and Java (although JavaScript is definitely closest), so if you have experience with either of those languages, the syntax should be familiar.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 31

Making the shift to ActionScript’s object-oriented programming ActionScript 3 is an object-oriented programming (OOP) language, which means, in general terms, that the fundamental structural unit of your applica- tion is an object. Objects expose specific functionality in the form of proper- ties and methods, which you use to interact with the objects.

If you have programming experience in earlier versions of ActionScript (1 or 2), the shift to ActionScript 3 may feel daunting. ActionScript 3 forces you to follow stricter OOP syntax when writing code, and you’ll notice throughout this book there is never a reference to _root or global variables. If you have a background in other object-oriented programming languages, such as Java or C++, you already have experience in writing OOP applications, and the shift to ActionScript 3 should be fairly painless.

Understanding objects and classes At the heart of object-oriented programming is the object, which encapsu- lates functionality. When an object is encapsulated, it has certain capabilities that it exposes through properties and methods you can use, but it hides all other details about how it does what it does. A class is the definition of an object. An object is one particular instance of a class. Each ActionScript class is defined in its own ActionScript file (with the .as file extension).

To illustrate the concept of a class, think about an employee within an orga- nization. An Employee class might contain the following properties:

firstName lastName socialSecurityNumber salary And, an Employee might have the following actions (methods) that it can perform:

The preceding lists include four properties and four methods of the Employee class. The basic Employee ActionScript class might look like the code in Listing 3-2.

Listing 3-2: The Employee Class with Four Properties and Methods package com.dummies { public class Employee ?3 { public function Employee() ?5 { //in the constructor you can initialize the object }

//define the public variables public var firstName:String; ?11 public var salary:Number;

//define the public methods public function doTask(task:Task):void { ?17 //do something to accomplish the task }

public function takeBreak(minutes:Number):void { } public function submitTimesheet(timesheet:Timesheet):void {

} public function complainAboutBoss():void { } } } Listing 3-2 defines the outline structure of your Employee class: ? 3 You name the class on Line 3, public class Employee, which defines the Employee class, and corresponds with the filename of the ActionScript file in your project. Because this class is named Employee, you have a file named Employee.as in your project.

? 5 The constructor is a special function that creates the object. When a new Employee is created by calling new Employee(); this con- structor (Lines 5–8) is called. In the constructor, you can do any kind of initial setup that your class needs.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 33

? 11 You define a few public properties in Lines 11–14. Other classes can use these properties to interact with the Employee class.

? 17 You also create public methods that are used to interact with the Employee class (Lines 17–31). These methods define all the things an Employee can do.

Defining getters and setters ActionScript has a special syntax to define getters and setters on a class, which are unique ways to combine the functionality of both a variable and a method. Although a getter or a setter looks like a normal variable to the out- side world, when it’s accessed, it runs a function. The easiest way to explain getters and setters is by describing the example in Listing 3-3.

Listing 3-3: Defining a Getting and Setter for hourlyRate public class Employee { public var salary:Number;

public function get hourlyRate():Number { } public function set hourlyRate(value:Number):void { this.salary = value * 40 * 50;

} } Listing 3-3 defines a getter and setter for the hourlyRate property of the Employee class. The hourlyRate getter isn’t a normal property, however, and is instead determined by the salary property. (In this example, we assume 40-hour workweeks and 50 workweeks in a year.) You can access getters and setters just as you access normal properties of a class. The following code creates a new Employee, sets the salary to $100,000 (we’re Flex developers, after all), and then uses the hourlyRate getter:

Because you defined hourlyRate as a getter, you can access it the same way you access a normal property. But when you access the hourlyRate getter, the function you defined runs and performs the calculation.

Because setters work the same way, you can have specific code that runs whenever a certain property is set. In Listing 3-3, the setter for hourlyRate calculates the yearly salary for that rate and sets the salary property.

Learning to love the black box An important concept in object-oriented programming is that every object is a black box, which exposes specific functionality but doesn’t let you peer behind the curtain to see the details of the implementation. When you pro- gram in an object-oriented language, you don’t need to worry about how a certain class does what it does; all you need to know is which methods and properties you can use. To illustrate this point, we apply the theoretical OOP principle to a real-life example.

If you’re like most folks, you have no idea how a microwave oven heats food. You know that seemingly magical invisible rays fly around, but that’s about the extent of your understanding. But you know how you’re supposed to use a microwave oven: You place food inside it, enter on a keypad the length of time you want the food to cook, and then press the Start button — and the food is then heated. To you, the microwave is a “black” box. Here’s a simple OOP example that illustrates this concept:

Within the warmUp method, any number of behind-the-scenes events can be happening. For all you know, a thousand gerbils running on treadmills generate an electric current that heats your food. But all you care about are the exposed properties and methods of the Microwave class. You know that you can call the addFood() method and pass in something for it to warm up. And, you know that you can set the time property, which determines how hot the Microwave makes the food. Then you call warmUp(), and you can assume that the Microwave will fulfill its side of the bargain and warm your food. You don’t need to know anything about molecular physics to get all those tasks to work. All these pieces, such as the time property and the warmUp() method, define the interface that you use to interact with the Microwave class. The interface is the collection of public properties and methods that a class exposes to the developer.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 35

Object-oriented programming is all about using the exposed interfaces defined by classes and not having to worry about how they do what they do. One out- standing benefit of this approach is that you can completely change the under- lying implementation without affecting the rest of your application. As long as the exposed methods and variables stay the same, all the behind-the-scenes implementation details can change.

Recognizing that packages are where classes live Classes are located in packages, which serve as a way to organize the ActionScript files in your project and to locate the classes within your code. The package of a class is the list of strings separated by periods that precede the class names. All Flex framework classes exist within the mx package, which means that the full package name of every class in the Flex framework resembles mx.subPackage.Class. For example, the full package structure of the Button class is mx.controls.Button. This example shows that the Button class lives in the controls package within the mx package.

When you create your own, custom ActionScript classes, you should use packages to organize your code. Picking a package structure involves orga- nizing your ActionScript files into a series of folders that match the package structure you want to use. You must also ensure that the package definition at the top of your ActionScript class matches the folder structure. The first line in any of your ActionScript classes defines the package for the class by using the package keyword followed by the full package name.

You can pick any package-naming structure you want, although a standard that’s often used is the reverse domain name syntax. It uses domain names to uniquely identify packages, but in reverse order. If you take a look at the first line in Listing 3-2, you see the use of the com.dummies package for the Employee class:

package com.dummies { In this line, the Employee.as source file is placed in the com/dummies/ directory within your project, as shown in Figure 3-3.You can use any package-naming scheme that you like; however, it is a common practice to group related classes together under the same package. As you work with the different components within the Flex framework, notice how they are grouped in logical packages, such as mx.controls and mx.containers.

Figure 3-3: Package structure corresponds with folder The package-naming convention you use is arbitrary, and if you choose to use the reverse domain style, it doesn’t mean that it needs to map to a real URL. The com.dummies package was used in the example, but that doesn’t have any true relationship to the dummies.com domain name.

Inheritance: Extending a class An ActionScript class can extend another class, which means that it inherits all the functionality of the class it’s extending. The class can then add func- tionality in addition to what was contained in the base class. In the Employee example in the previous section, you can split the Employee class into two classes. First and foremost, an Employee is a Person, which has certain prop- erties, such as firstName and lastName. The following listing contains a simple Person class:

package com.dummies { public class Person { } } Now that you have a Person class that contains the firstName and lastName properties, you can make the Employee class extend Person, and you can remove the firstName and lastName properties from Employee because they’re contained in Person. Here’s a portion of the new Employee class:

package com.dummies { public class Employee extends Person { …

Chapter 3: Flexing Your Muscle with MXML and ActionScript 37

Now that you have the base Person class, you can make other classes that also extend Person. For example, you can make a Boss class that defines the specific functionality of a Boss. The Boss class is shown in Listing 3-4.

Listing 3-4: The Boss Class Extends Person package com.dummies { public class Boss extends Person { public var employees:Array;

public function giveRaise(employee:Employee, percent:Number):void { employee.salary = employee.salary + (employee.salary * percent);

} public function giveRaiseToAll(percent:Number):void { for(var i:int=0; i

} } } } Because Boss also extends Person, you don't have to create the firstName or lastName properties; it inherits those properties just like the Employee class does. But the Boss class contains all elements specific to a Boss. In this example, a Boss has a list of employees and can give raises (which, in an ideal world, the boss would do).

Understanding interfaces An interface, which is a special kind of ActionScript file, is similar to a class but doesn't define any specific implementation details. An interface defines a list of methods, but unlike a class, the interface doesn't have any code to define how the method works. Instead, classes are supposed to implement the interface, which means that the class must include all methods defined in the interface. The following code snippet defines a simple interface named IPayee that has a single function named receiveMoney:

The interface looks similar in structure to a class; however, notice in the third line the use of the word interface rather than the word class. The interface defines a function, although you can see the lack of a public, private, or protected keyword. A class that implements an interface must implement all functions defined in the interface as public functions. You can define only public methods within an interface, not properties. However, because getters and setters are methods, you can define those in an interface as well.

You can modify the Employee class to implement the IPayee interface. To do so, you need to add the implements keyword to the class definition, and you create a method named receiveMoney:

public class Employee extends Person implements IPayee { public function receiveMoney(amount:Number):void { trace(“I'm rich!”);

} To understand the benefit of using interfaces, imagine which kinds of entities the Boss class you created might have to pay. Obviously, all employees need to get paid, but also, possibly, merchants, utility companies, and govern- ment tax boards, for example. In this context, each of these entities could be a completely different class, but they can all implement the IPayee interface, which indicates that each class can receive money. The Boss doesn't need to know about each different class that needs to be paid; instead, the Boss knows only about the IPayee interface, and can know how to interact with any class that implements that interface.

Exploring static methods and variables If a method or variable has the static keyword before the method or vari- able name, it behaves differently from normal variables or methods of the class. Static methods and variables belong to the class itself, not to any par- ticular instance of the class. When you call a static method, you're calling a method on a class, as opposed to a method on an object.

The code in Listing 3-5 creates the CustomMath class, which has two static functions: one for returning the sum of an array of numbers and another for returning the average.

After those static methods are defined in the CustomMath class, you can invoke them by calling CustomMath.sum() and CustomMath.average() — for example, var avg:Number = CustomMath.average(3, 4, 5). You never create a new instance of the CustomMath class. This usage is wrong, for example: var math:CustomMath = new CustomMath().

Chapter 3: Flexing Your Muscle with MXML and ActionScript 39

Listing 3-5: Creating a Class with Two Static Functions package { public class CustomMath { public static function sum(numbers:Array):Number { var sum:Number = 0;

for(var i:int=0; i

} } } A few main static methods and variables are built into the Flex framework that you will use. The following list describes a few of the most common ones you see while building Flex applications: Application.application: You can always access the main Application object that is the root of your Flex application by using the static variable Application.application.

Alert.show(): The Alert class lets you display pop-up dialog windows by using the Alert.show static function. The following line pops up a window with the title Error and the message Houston, we have a problem.

PopUpManager: The PopUpManager class contains a set of static meth- ods that let you work with your own, custom pop-up windows. The main methods you use are addPopUp, removePopUp, and centerPopUp.

Math: The Math class has a whole series of static math functions, such as min, max, sin, and cos. For example, to compute the lesser of two numbers (defined as variables x and y), you can call var min:Number = Math.min(x, y);

System.setClipboard(): You can set the text that's on the user's Clipboard by calling System.setClipboard(“text to set”). Note that for security reasons, you cannot get text from the Clipboard; you can only set it.

Comparing ActionScript and JavaScript ActionScript and JavaScript are similar languages, and both are based on the same language specification, ECMAScript. The main difference is that ActionScript is an implementation of a newer draft of the ECMAScript stan- dard, Version 4. But because both JavaScript and ActionScript are based on the same base specification, the syntax you use is similar.

One big difference between the two languages involves the strict-typing of ActionScript 3, which supports compile-time type checking. When you declare a variable, you specify which type of variable it is — a String or Number or any custom class you might be using. The following line of code declares a variable named myDate that is a Date:

Because the myDate variable is declared as a Date object, if you try to assign any value that isn't a Date, the compiler catches it and notifies you. So, the following line generates a compile-time error:

myDate = 5; //won't work because 5 is a Number, not a Date

Having this type of compile-time type checking might not seem like a big deal, but it's invaluable for writing bug-free code. Without compile-time type checking, you can easily write code that makes mistakes that go uncaught. These types of errors would crop up eventually, but only at runtime when you're debugging your application. Compile-time type checking forces you to write clear, structured code that's less prone to errors.

Understanding the Relationship between ActionScript and MXML Every MXML tag is actually ActionScript code behind the scenes. Each of the components in the Flex framework is written in ActionScript. When you compile a Flex application, the compiler translates all the MXML code into pure ActionScript code, which is the code that is then compiled and run. MXML is just a shortcut that makes certain tasks, such as laying out the pieces of the user interface in your application, much easier than having to code the comparable ActionScript by hand. But you should understand that anything you can do with MXML markup, you can also do with ActionScript. Depending on the task, some tasks are easier to do with MXML markup, and some are easier (or only possible) with ActionScript.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 41

MXML helps most in two areas: Application design: MXML simplifies application design when you're composing the visual layout of your applications.

Data binding: MXML lets you use data binding with a simple tag-based syntax. For more on data binding, see Chapter 12.

The following example illustrates how to simplify the layout of your application. Listing 3-6 creates a simple Flex application with a Panel container that contains an Image.

Listing 3-6: Using MXML to Create and Lay Out Your Application

The entire sample application in Listing 3-6 consists of six lines of MXML code. You can create exactly the same application by using almost all ActionScript code, and it would look like the code in Listing 3-7.

Listing 3-7: Using Pure ActionScript to Create and Lay Out Your Application

Listing 3-7 (continued) } ]]>

This listing produces exactly the same application, but it needs four times as many lines of code, which highlights what makes MXML so useful.

Working with the Event Model The Flex framework relies heavily on events as the preferred method of commu- nication between components. An event is an announcement that something has happened. This “something” might be a mouse click or a notification that a file has finished downloading or anything else that a component wants to tell other components about. Events are a fundamental part of the Flex framework, and you must properly understand how the event model is supposed to work in Flex applications.

All components in the Flex framework define specific events that you can listen for. When something happens within a component that it wants to announce, such as a button click, the component dispatches an event. Dispatching an event is a way to announce that something has happened to all the other parts of your application.

The Button control is a good example for exploring the event model. The Button control primarily displays a button with some text and lets the user click it. An application that uses a Button control doesn’t know anything about what happens when the user interacts with the Button. For instance, an appli- cation doesn’t care how the Button draws itself when the mouse rolls over or off. All you need to pay attention to are the events that the Button dispatches. The most important event that a Button dispatches is probably the click event. When the Button is clicked, it dispatches a new event to announce that it was clicked. The Button is responsible only for making that announcement and doesn’t care which other parts of your application, if any, are listening for the announcement.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 43

the user clicks the control, it dispatches the click event, but the dispatching of that event doesn’t do anything on its own. In your application, you attach a listener to the click event, which is a function that`s run when the event fires. After you add a listener, the code within your listener method runs every time that particular event is dispatched.

The words listener and handler are often used interchangeably when talking about events. Adobe has a set of coding guidelines that define their best prac- tices for writing ActionScript 3 code. These best practices recommend names for your event listener methods, such as eventNameHandler, which is the convention we use in this book. So, an event listener for a mouse-down event would be named mouseDownHandler. To review the best practices guide- lines, visit http://opensource.adobe.com/wiki/display/flexsdk/ Coding+Conventions.

Adding event listeners with MXML The easiest way to add event listeners to Flex components is to add MXML attribute listeners. You add event listeners in a similar way as you define properties or styles in the MXML tag. But event listeners are different than properties and styles, because they define ActionScript code that’s run when the event fires. You can add a listener to the click event of a Button control, like this:

The click and label are both MXML tags, but the label tag defines a property and the click tag defines an event listener. Event listeners defined inline in this way consist of ActionScript code that’s executed when the event fires.

You don’t have to point only to a function to handle the event; you can write ActionScript code directly in the MXML tag, if you want. For instance, the fol- lowing example displays an Alert message by using ActionScript code directly in the click MXML tag:

show(`You clicked!’)” /> However, as a general practice, code is often much more readable and man- ageable if you always use functions defined outside the MXML tag as your event listeners.

Examining the structure of an event listener The event listener defined in your ActionScript code should be a function that takes a single Event object parameter. Your functions generally look like this:

private function eventHandler(event:Event):void { //do your event handling stuff here }

Notice that the event parameter is an Event object. Event handlers are always passed an Event object that has a few important properties. Most importantly, the Event object has a property named target that identi- fies the component that dispatched the event. Be aware also of a different property named currentTarget. The differences between target and currentTarget are discussed later in this chapter, when we cover event bubbling. For now, just know that you can use target to get a reference to the component that dispatched the event.

The following example displays two buttons, both of which use the same event listener for the click event. The event listener uses the target prop- erty to get a reference to the particular Button control that was clicked, and then displays an Alert pop-up message showing the label of the Button.

} ]]>

Chapter 3: Flexing Your Muscle with MXML and ActionScript 45

on the component. Explicitly casting it to a Button lets you access the Button-specific properties of the object, such as label.

Event is the base class for all events, but more specific classes also extend Event to provide more detailed information about particular kinds of events. For example, mouse interaction events use the MouseEvent class, which adds the localX, localY, stageX, and stageY properties that define the coordi- nates, relative to the component and the stage, of the mouse when the event was dispatched.

The example in Listing 3-8 adds a listener to the change event of a horizontal slider control. When the HSlider dispatches the change event, it dispatches a SliderEvent event, which has a few specific properties that tell you more about the interaction with the slider. In this example, you can access the value property of the event to get the latest slider value.

Listing 3-8: Adding a Listener to the Change Event of a Slider Control

private function changeHandler(event:SliderEvent):void { } ]]>

Many Flex components dispatch their own custom events, so they can indicate this type of detailed information. The documentation for each of the components in the Flex framework explains all the different events that each component dispatches. Giving you a comprehensive list of all events and event types is beyond the scope of this book, although in Part III, we touch on the common events for many of the framework controls.

Adding event listeners with ActionScript You can also add event listeners with ActionScript rather than with MXML tags. All Flex components have a method named addEventListener that you can use. When you call addEventListener, you have to specify which event you’re listening for and the handler function that runs when the event is dispatched. The example in Listing 3-9 creates ten Button controls when the application first loads and adds a click event listener to each one.

Listing 3-9: Adding an Event Listener with ActionScript

private function createButtons():void { for(var i:int=0; i<10; i++) { box.addChild(button);

} } private function clickHandler(event:Event):void { } ]]>

When you add the click event listener with ActionScript, you use MouseEvent. CLICK as the event type. This static variable is defined by the MouseEvent class. The MouseEvent.CLICK variable translates to the string click. You can add However, when you add event listeners with ActionScript, you should always use the static variables instead, such as MouseEvent.CLICK. Using the static variables ensures that you don’t have any accidental typos in your code, and your code benefits from proper compile-time checking. If you used a string to represent the event type, the compiler can’t help look for potential problems. For example, you might type the following line:

button.addEventListener(“rollover”, rollOverHandler) The proper event name, however, is rollOver (notice the capitalization difference). If you use MouseEvent.ROLL_OVER rather than the string, you can always be sure that you’re using the correct event type. So, rather than “rollOver”, the proper way to add the event listener is

Chapter 3: Flexing Your Muscle with MXML and ActionScript 47

One benefit of using ActionScript to add event listeners is that you can remove them by using the removeEventListener method. Only listeners that are added with the addEventListener method can be removed; you cannot remove event listeners that are added with inline MXML tags. If you later want to remove the click listener that you added on one of those but- tons, you can add this line:

button.removeEventListener(MouseEvent.CLICK, clickHandler) Understanding event propagation When an event is dispatched by a component, it propagates up and down the hierarchy of components in your application. During the propagation of a single event, three phases make up the event life cycle: capture, target, and bubble. Event listeners can register and receive notification at any of these three phases: Capture: This phase is the first phase, but is rarely used. In the capture phase, the Event begins at the top-level parent component and works its way down the display list until it reaches the target component that dis- patched the event. In the hierarchy shown in Figure 3-4, the Event begins in the capture phase at the Panel and then moves down to the Hbox and then down to the Button.

When you add an event listener, you have to specify whether the listener should listen in the capture phase. The third parameter in the addEvent Listener method is a Boolean value that determines whether the capture phase is used (it defaults to false). To add a listener to the Button control on the capture phase, you can use the following line of code: button.addEventListener(MouseEvent.CLICK, clickHandler, true);.

For most event handling in your applications, you never need to use cap- ture phase listeners. Unless you need extremely aggressive event han- dling for some reason, you can probably just stick to target and bubble phase listeners.

Target: Because the Button control was the component that dispatched the event, after the event propagates down to the Button, it reaches the targeting phase. This phase is used only for event listeners that target and event.currentTarget are the same).

Bubble: After reaching the targeting phase, the event then propagates back up the display list in the bubbling phase. In the example, the event hits the HBox and then the Panel while bubbling. The order of the bubble phase is the opposite of the capture phase.

Figure 3-4 shows the propagation of an event through the three phases as it travels down the display list and back up.

Figure 3-4: The propa- 1. Capture 3. Bubble gation of a single event through the capture, 2. Target target, and bubble phases.

At any point in your event listeners, you can figure out which phase is active by inspecting the eventPhase property of the Event. The example in Listing 3-10 demonstrates the complete propagation of a single click event. The example adds click event listeners to the Panel, HBox, and Button. When the click event fires. the event listener uses trace() to output debugging information about the event.

Listing 3-10: An Example to Debug Event Propagation

} private function clickHandler(event:MouseEvent):void { trace(“phase: “ + event.eventPhase + “ | target: “ + event.target + “ | currentTarget: “ + event.currentTarget);

Chapter 3: Flexing Your Muscle with MXML and ActionScript 49

When you run the code in Listing 3-10 and click the button, you see the following debugging output:

phase: 1 | target: app.panel.hbox.button | currentTarget: app.panel phase: 1 | target: app.panel.hbox.button | currentTarget: app.panel.hbox phase: 2 | target: app.panel.hbox.button | currentTarget: app.panel.hbox.button phase: 3 | target: app.panel.hbox.button | currentTarget: app.panel.hbox phase: 3 | target: app.panel.hbox.button | currentTarget: app.panel

This chunk of code shows the complete propagation of a single click event. In the sample output, the event phases are displayed as the numbers 1, 2, or 3, which correspond with the capture, target, and bubble phases. The event begins in the capture phase at the top-level Panel container and then travels down the display list, still in the capture phase, to the HBox container. The event then reaches the Button control, and because the Button is the compo- nent that dispatched the event, the event is now in the target phase. (Notice that the target and currentTarget properties of the event are the same.) The event then travels back up the display list in the bubble phase, hitting the HBox first and then the top-level Panel container.

At any point in the event propagation cycle, you can call stopPropagation() or stopImmediatePropagation() on the event, which stops the event in its tracks. The stopImmedaiteProgpagation() event stops the event right away, and no other listeners that are registered for that event are called. If you call stopPropagation() instead, any other event listeners for that event on the same component are executed, but the event doesn’t move any farther up or down the display list.

Listening for some common events All components in the Flex framework dispatch a few useful events. The following list describes a few of the common events you might use in your applications: show, hide: Whenever a component’s visible property is changed, either the show or hide event fires.

move, resize: These events are dispatched when the component’s location or dimensions are changed.

initialize, creationComplete: These events indicate when a com- ponent starts and finishes the creation process (including the creation of child components). If you have some ActionScript code that needs to run after all the child components have been created, be sure to use the creationComplete event (see Listing 3-10).

change: Many Flex components let the user change a selected value, such as the slider controls and the NumericStepper. Many of the con- trols in the framework will dispatch a change event to notify you that a change has occurred.

90 VISUALIZAÇÕES DOWNLOAD