SlideShare a Scribd company logo
A Deep Dive into the Flex 3 Framework Brad Umbaugh RJ Owen EffectiveUI November 18, 2008 Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Introductions Who are we? Brad Senior Developer at EffectiveUI, builds lots of cool stuff, looks a little like John Stamos. RJ Senior Developer at EffectiveUI, Adobe Community Expert, falls asleep when he drinks wine Who are you? Assumptions: You know some Flex You want to know more Flex You know how to get things done with Flex, but not how to make the most of the Flex Framework Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
What will we talk about today? Several topics that help you maximize Flex’s power (grr!!) Things many beginner - intermediate developers don’t know a lot about Data Binding Style manager Collections System Manager For each of these, we’ll discuss: What it is How it affects you Best ways to use it Common mistakes to avoid It’ll start simple, and get deeper as we go Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Data Binding ®
The Problem Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Need a way to sync views with changing data ®
The Scenario Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Scenario: A value object with some text that should be displayed on a label ®
Roll-my-own solution I have a VO that contains some text I need to display on the screen Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  public class BoringVO1 { public var _text : String; } ®
Roll-my-own solution How will I know when the text field on this object changes?  I’ll have it dispatch events. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  [Event(name=”textChanged”), type=”flash.events.Event”] public class BoringVO1 extends EventDispatcher { private var _text : String; public function set text( value : String ) : void { _text = value; this.dispatchEvent( new Event(“textChanged”) ); } } ®
Roll-my-own solution In the view, I’ll listen for those events: Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  public function setMyText() { theLabel.text = value; } <mx:Label id=”theLabel”/> private var _vo : BoringVO1; public function set vo( value : BoringVO1 ) : void { _vo = value; _vo.addEventListener( “textChanged”, this.setMyText ) } ®
Roll-my-own solution Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Ugh.  Annoying.  Too much code for so simple a task. ®
Flex’s solution: data binding Data binding is a contract between two objects: one promises to dispatch events when its data changes, and another promises to listen to those changes and update itself Got this definition from Michael Labriola’s fantastic data binding talk at 360|Flex San Jose, “Diving in the Data Binding Waters” Contrary to popular belief, it isn’t magic: it’s events! Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Flex’s solution: data binding Mark the object and its property as [Bindable], use curly braces, and away you go. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  <mx:Label id=”theLabel” text=”{vo.text}”/> [Bindable] public var vo : BoringVO1; public class BoringVO1 { [Bindable] public var text : String; } The VO! The app! ®
The Basic Idea A property of a component changes The property’s component fires off an event indicating that the property changed Other components listen for this event, recognize that a needed value has changed, and update themselves with the new value Bindings also fire once on initialization, so that initial values are set correctly Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
MXML Example (with curly braces), binding to a property To bind to a property, simply put a reference to the property in curly braces: <mx:Label text=”{anObject.text}”/> The referenced data must be marked as bindable: give it [Bindable] metadata If it isn’t marked as [Bindable], you’ll get a warning from the compiler... “Data binding will not be able to detect assignments...” ...and the binding won’t work. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  A warning! ®
Metadata What is it? Metadata is information that tells the compiler how components are used in a Flex application. Various kinds: [ArrayElementType], [DefaultProperty], [Deprecated], [Effect], [Embed]... [Bindable] metadata tells the compiler to generate code to dispatch events when the property or properties marked [Bindable] are changed, so that other objects binding to that data will update accordingly. Why is it needed? Remember all of the event dispatching and listening from the roll-my-own example?  The [Bindable] metadata tells the compiler to dispatch all of those events when objects or their properties change. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Metadata Where should [Bindable] metadata be placed? Before a public class definition Makes all public properties, public getters/setters available as binding sources Before a public, protected, or private property defined as a variable Makes that property available as a data binding source Before a public, protected, or private property defined as a getter/setter Makes that property available as a data binding source Components declared in MXML are automatically set as [Bindable] in the compiler-generated Actionscript, as long as they have an id set Example: DataBinding4.mxml / DataBinding4-interface.as What is the syntax? [Bindable] or [Bindable(event=“eventTypeToWhichInterestedComponentsShouldRespond”)] If no event type is given, by default an event named “propertyChange”, of type PropertyChangeEvent is dispatched Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Metadata Why use a custom event type?  It’s more efficient than using the default PropertyChangeEvent More on this later Who dispatches the custom event? When no custom event type is specified: Default PropertyChangeEvent is dispatched automatically Example: DefaultEventFiring.mxml When a custom event type is specified: No PropertyChangeEvents are dispatched Custom event types are not dispatched automatically Must dispatch custom events explicitly Example: CustomEventFiring2.mxml Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
MXML Example (with curly braces), binding to a function Functions can be used as a source for data binding Must be marked with appropriate metadata: [Bindable(event=”eventType”)] When do bindings to functions execute? Whenever the event type listed in the [Bindable(event=”eventType”)] metadata is dispatched  Example: DataBinding6.mxml Whenever one of the bindable arguments passed in to the function changes Code automatically generated to execute the binding whenever one of the function’s passed-in bindable arguments changes Compiler will throw a warning when non-bindable arguments are passed in to the argument list of a bound function (and the binding won’t work, either) On initialization Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
MXML Example (with curly braces), binding to XML data Can bind directly to XML data XML does not dispatch change events when nodes are edited, so views may not update correctly XMLListCollection is the class of choice to use as an XML data provider Provides sorting and filtering methods Ensures views get updated when XML nodes are edited Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
MXML Example: using <Binding> tag The MXML <Binding> tag accomplishes the same thing as curly braces Allows you to bind multiple sources to a single destination Can place a concatenated Actionscript expression in curly braces in the source property of a <Binding> tag Example: BindingTag.mxml Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
What does the generated code buy you? Brevity Lots of error handling Binding to expressions Compiler generates code to evaluate the expression placed in curly braces when particular events are fired off; makes it very easy to bind to complex expressions <mx:Label text=”{a.toString() + b.toString() + “: “ + (c/d).toString}/> Chains Binding to property chains happens easily, too: <mx:Label text=”{this.childA.propertyB.childC.widgetD.text}”/> When childA, propertyB, childC, or widgetD changes, the label’s text updates appropriately All of the event listeners needed to make this happen are created for you in the generated code All of the properties in the chain must be [Bindable] in order for this to work correctly Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Binding in Actionscript: bindProperty() and bindSetter() Bindings can be created in Actionscript code, too Use mx.binding.utils.BindingUtils Two important static methods on the BindingUtils class bindProperty() sets a destination property when a source property or property chain changes Takes a destination object, a destination property, a source object, and a source property chain (remember to make all elements in the source property chain [Bindable]) You  can  use bindProperty() to set a property that has a setter bindSetter() calls a handler function() when a source property or property chain changes Takes a handler function, a source object, and a source property chain Since handler functions fire when bindSetter is first called; be sure to check for nulls  Handler function receives, as a parameter, the new  value  of the source’s property chain Both of these functions return a ChangeWatcher object; use this to manipulate the binding after it has been created (change handler function, change objects, etc) Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Common problem: performance in Cairngorm Too many bindable fields on the model doesn’t perform well! Why? Every time one of the properties on the model changes, the model dispatches a PropertyChangeEvent Any component binding to any property on the model listen for PropertyChangeEvents dispatched from the model Examines the event to see which property the PropertyChangeEvent is for; disregards if not relevant If the model has a lot of fields, this is a huge amount of unnecessary work Solution?  Custom event types Listening components now only receive the particular event type dispatched for the property in question Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Common problem: two-way binding Problem: two fields should update each other Simple solution: Create two bindings, one in each direction.  Flex makes sure that an infinite loop won’t occur  MXML solution: TwoWayMXML.mxml Actionscript solution: TwoWayActionscript.mxml There’s a shortcut for this coming in Gumbo (Flex 4)... Curly braces <mx:TextInput id=”firstInput”/> <mx:TextInput id=”secondInput” text=”@{firstInput.text}”/> Binding tags <mx:Binding twoWay=”true” ... Check out the Gumbo spec:  http://opensource.adobe.com/wiki/display/flexsdk/Two-way+Data+Binding Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Common problem: making whole objects [Bindable] instead of individual properties Imagine a complex graph, with thousands of data points If each point on that graph is an object (VO), any time any point on the object changes it dispatches a property change event. This can get incredibly expensive really fast when there are lots of objects sitting around in memory. Whenever possible, make single properties [Bindable] instead of entire objects. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  StyleManager ®
StyleManager: Styling 101 “Styles” differ from “Properties” in the way they are set, maintained, and accessed in your application Ways to set styles: In MXML, they look just like properties: <mx:Label  text=&quot; woot! WTF FTW! &quot; color=&quot; 0x00ff00 &quot; width=&quot; 100 &quot; /> In Actionscript, they must be set through the style manager: var  label : Label =  new  Label(); label.text =  &quot;woot! WTF FTW!&quot; ; label.setStyle( &quot;color&quot; ,  &quot;0x00ff00&quot; ); Why is it more complex in ActionScript? Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
StyleManager: Styling 101 Styles are inheritable Styles must propagate to their children, and their children’s children, and sometimes their children’s children, forever and ever. Styles are like genes! This task requires some management The flex team built a class to do just that, and creatively named it the Style Manager. The StyleManager serves as the storehouse for all of this information and makes it available to other components. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
StyleManager: Styling 101 Every time a style is set, the framework has to keep track of: Any parent styles this over-rides Any children who are affected Flex adds/removes styles through proto chaining Style properties are stored in the proto chains - not as properties on the objects themselves proto chains are outside of the scope of our discussion, but it’s a really interesting topic to learn more about. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Style Precedence Global, Type, Class, Attribute Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Text *Image courtesy Juan Sanchez and Andy McIntosh ®
Adding styles to components in AS3 To add styles to individual components, use UIComponent.getStyle and setStyle getStyle is cheap - it just reads the style information setStyle is expensive - it has to traverse the entire style tree and re-calculate inheritance. These methods inherently make use of the StyleManager These should satisfy your styling needs on a component level Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Using StyleManager to manage Assets You can embed assets through the StyleManager Advantages: Avoid cluttering your component code with Embed statements Keep all external resource paths in a single place Manage resources that might be used in more than one part of your app .icons { wrenchIcon :  Embed ( 'images/wrench.png' ); searchIcon :  Embed ( 'images/search.png' ); loginIcon :  Embed ( 'images/login.png' ); } <mx:Button icon=&quot; { StyleManager.getStyleDeclaration( '.icons' ).getStyle( 'wrenchIcon' ) } &quot; label=&quot; Customize &quot; /> Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Using the StyleManager Other things you can do with the StyleManager: Make changes to existing styles Useful for programmatically re-themeing at runtime for a configurator StyleManager.getStyleDeclaration(selector); StyleManager.setStyleDeclaration(selector, CSSSelector, update); Clear existing styles StyleManager.clearStyleDeclaration(selector,  update) Define whether your styles influence other components StyleManager.registerParentSizeInvalidatingStyle(styleName:String) StyleManager.registerParentDisplayListInvalidatingStyle(styleName) Register aliases for color names “ blue” instead of 0x0000ff StyleManager.registerColorName(colorName, colorValue); Load styles from a swf at runtime StyleManager.loadStyleDeclarations(...); Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Load style declarations at runtime Uses different CSS files for the different themes Load the style declarations from a pre-compiled swf The core of the functionality: private   function  changeCSS( panelTitle:String, name:String ): void  { StyleManager.loadStyleDeclarations( name,  true  ); } Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Example: swap styles from a SWF at runtime Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Example courtesy of Juan Sanchez and Andy McIntosh ®
Example: swap styles from a SWF at runtime Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Example courtesy of Juan Sanchez and Andy McIntosh ®
Example: clearing and restoring styles Same example as before, but a few new buttons / handlers: Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  public   function  unloadRed(): void { StyleManager.unloadStyleDeclarations( 'Red.swf' ); } // Code to restore the default 'Halo' button public   function  restoreDefaults(): void { StyleManager.setStyleDeclaration( 'Button' , defaultButtonStyle,  true ); } private   var  defaultButtonStyle : CSSStyleDeclaration; public   function  onComplete(): void { defaultButtonStyle = StyleManager.getStyleDeclaration( 'Button' ); } ... <mx:Button  label=&quot; Go Red! &quot; click=&quot;loadRed()&quot; /> <mx:Button  label=&quot; Go Blue! &quot; click=&quot;loadBlue()&quot; /> <mx:Button  label=&quot; Clear &quot; click=&quot;clearStyles()&quot; /> <mx:Button  label=&quot; Restore &quot; click=&quot;restoreDefaults()&quot; /> <mx:Button  label=&quot; Unload Red &quot; click=&quot;unloadRed()&quot; /> ®
Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  StyleManager demo: ThemeSwap http://www.scalenine.com/samples/themeSwapper/themeSwap.html ®
In case it doesn’t work live: “Obsidian” theme Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
In case it doesn’t work live: iTunes 7 Theme Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
In case it doesn’t work live: Windows Vista theme Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
More info? Creating Visual Experiences with Flex 3.0 , by Juan Sanchez and Andy McIntosh Still valid in Flex 4.0! Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ScaleNine! Scale....ten? ®
Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Collections ®
What is a collection? Data comes in many formats Objects Arrays XML There are many different kinds of view components Crossing all of the view components with all of the different types of data representations would yield an unmanageable number of classes Need a common way to use any data as the source for any view component This is where mx.collections.* shines Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Why do we need collections? Collections: Abstract the format of the data from the display component Ensure components are updated when data changes Provide consistent operations to use on data Provide sorted views of data Provide filtered views (Reasons taken from the online flex documentation at  www.adobe.com ) Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
So, what are collections really? Classes that implement IList, ICollectionView IList is an interface that contains that make it easy to work with linear data ICollectionView is an interface that makes it easy to work with hierarchical data ArrayCollection & XMLListCollection are the main ones you’ll use These actually extend ListCollectionView, which implements IList and ICollectionView Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
IList Interface for working with linear data Interesting methods: addItem addItemAt getItemAt getItemIndex removeAll removeItemAt setItemAt Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
ICollectionView Interface for sorting, filtering, and interacting with linear and hierarchical data Interesting properties sort filterFunction Interesting methods contains createCursor Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
ListCollectionView Implements IList Implements ICollectionView Consequently, components extending ListCollectionView can be used anywhere an IList or an ICollectionView is expected  Is the base class for ArrayCollecton, XMListCollection Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
ArrayCollection, XMLListCollection The two classes in the Flex framework that inherit from ListCollectionView ArrayCollection Uses an array as its data source Good for linear data XMLListCollection Uses an XMLList as its data source XMLList is a list of one or more XML objects Good for hierarchical data Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Where are collections useful? Various classes can all use collection objects as their data source; these are called “data provider components”: ButtonBar ColorPicker ComboBox DataGrid DateField HorizontalList LinkBar List Menu MenuBar PopUpMenuButton Tree etc. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Review: why do we need collections? Collections: Abstract the format of the data from the display component Ensure components are updated when data changes Provide consistent operations to use on data Provide sorted views of data Provide filtered views Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
1.  Abstract the data format The <mx:TileList> can accept many different types of data sources, including an ArrayCollection and an XMLListCollection The component can swap between different collections without a problem Example: AbstractDataFormat.mxml Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
2.  Update views when data changes One of the main reasons to use collections is so that when the data contained by the collection changes, views update accordingly Collections fire off CollectionChange events when their items change; views listen for these events and refresh themselves accordingly When passing in non-collection objects as data providers, you may not see the view update immediately Flex wraps the passed in “raw” objects (e.g., Array or XML) in collection objects; this lets you use your raw data directly. However, changes made directly to those raw objects may not force the views to update Example: UpdateTheViews.mxml Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
3.  Consistent data manipulation operations Both ArrayCollection and XMLListCollection inherit from ListCollectionView This makes it easy to edit data in a consistent way, regardless of which type of data is being used for the data provider Square brackets [] (Don’t use these - they’re involved in a Flash Player bug regarding loading sub-applications; use getItemAt() intead) getItemAt() removeItemAt() addItem() Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
4.  Sorted views Collections provide a mechanism to sort the view of the data without changing the underlying data itself ListCollectionView’s sort property: type = Sort sort.fields should be an array of SortField objects, which describe how to perform the sort Call refresh() on the collection object after assigning it a sort object Underlying data does not change Example: SortingViews.mxml Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
5.  Filtered views Collections also offer an easy way to filter data Simply set the filterFunction property on the collection to a function of the form: function theFilterFunction( item : Object ) : Boolean {} The function should return true on the object if it should be included in the filtered view of the data Example: SortingViews.mxml Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Hierarchical Data Representing hierarchical data in XML is trivial, since XML itself is natively hierarchical: <Foods> <Nuts> <Nut>Peanut</Nut> </Nuts> </Foods> Object graphs can be used, too Example: ObjectHierarchy.mxml Put the child objects in the “children” field of the object Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Cursors Classes used to navigate through collection objects Provide convenient, consistent ways to access data in collections Initialize to the first element in the collection Cursors allow: Movement through data (forward, back) Searching (only if the collection is sorted) Bookmarks Data manipulation (addition, removal) Great for navigating and searching through data They respect sorts (even though the underlying data isn’t actually sorted, cursor will behave like it is) They have an optimized find method Handy for paging through long results sets Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Common Problem: Manipulating a view component immediately after changing the data provider Setting the dataProvider property on a component such as a Tree requires that it validate its properties and layout; it may need to add or remove children based on the changes Attempting to manipulate the view component immediately after setting the dataProvider (i.e., on the next line of code) can cause runtime errors because the component has not yet validated its properties and layout To get around this problem, call validateNow() on the view component immediately after setting the dataProvider This forces the component to validate its properties and layout and redraw itself if necessary Only do this when necessary; there’s a performance hit Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Common Problem: Not seeing expected changes in the view If the objects stored in a collection are not [Bindable], the view will not be able to detect when they have changed In these instances, after updating an item in the collection, call the itemUpdated method on the collection, letting it know that its data has changed Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  SystemManager ®
SystemManager: overview “Root” of the Flex swf First class that is instantiated Controls and coordinates the initialization of the application Instantiates and displays the pre-loader Instantiates Application and adds it to the display list Manages layers of children for popups (sorta), cursors, and tooltips Switches focus between top-level items like the above list Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
SystemManager: 2 frame swf Flex apps currently publish to a 2 frame SWF 1st frame (small):  SystemManager , Preloader, DownloadProgressBar, helper classes. 2nd frame (probably big): The rest of the framework, your application, embedded assets Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  SystemManager Preloader DownloadProgressBar HelperClasses Flex Framework Application code Embedded Assets Frame 1 Frame 2 RSLs ®
SystemManager: 2 frame walkthrough Frame 1 streams in, plays SystemManager is created SystemManager takes over - creates Preloader Preloader tracks the rest of the bytes streaming in, provides updates to SystemManager Once all bytes for frame 2 are streamed in, frame 2 plays Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  SystemManager Preloader DownloadProgressBar HelperClasses Frame 1 ®
SystemManager: 2 frame walkthrough Frame 2 plays SystemManager instantiates Application, sets Application.systemManager to itself Application initializes itself, emits CreationComplete SystemManager adds Application to the DisplayList, hands control over to Application / LayoutManager applicationComplete event is dispatched, and your app is ready to go Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  Flex Framework Application code Embedded Assets Frame 2 RSLs ®
SystemManager: what is it good for? Dispatches browser-resize events Detecting if assets have been embedded Fonts, for example.  If the font isn’t embedded, use a different font. SystemManager.embeddedFontList; Displaying your own preloader and... Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
SystemManager: what else is it good for? Getting a reference to the root object SystemManager.stage Flash converts have probably spent some time looking for this Monitoring keyboard and mouse activity Manipulate multiple pop-ups, cursors, or tool-tips from their parent Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
SystemManager Pitfalls: Multiple Child Lists PopUp windows added through PopUpManager.addPopUp or createPopUp do not go on the SystemManager.popupChildren list by default - they go on the normal Application child list. This list is displayed above the Alert child list and toolTipChildList To add them there, pass the constant PopUpManagerChildList.POPUP as the fourth parameter to the add or create methods on PopUpManager PopUpManager.createPopUp( this , TestPopUp, false , PopUpManagerChildList.POPUP); cursorChildren are on top of everything, then popupChildren, then toolTipChildren, then the regular old application children. Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ® application children toolTipChildren popupChildren cursorChildren
SystemManager Pitfalls: The Root The system manager tries to own “_root” May manipulate the root object in ways you’re not expecting in Flash This makes flash / flex integration frustrating at times I’m not going to go into this more, but be aware of it Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Resources Michael Labriola’s 2008 360|Flex San Jose talk about Data Binding: “Diving in the Data Binding Waters” (http://www.onflex.org/ted/2008/08/diving-in-data-binding-waters-with.php) Flex 3 Cookbook  (Joshua Noble & Todd Anderson; O’Reilly) Creating Visual Experiences in Flex 3.0  (Juan Sanchez and Andy McIntosh; Addison-Wesley) Programming Flex 2 ,  Programming Flex 3  (Chafic Kazoun, Joey Lott; O’Reilly) Learning Flex 3  (Alaric Cole; O’Reilly) Online Flex documentation API:  http://livedocs.adobe.com/flex/3/langref/index.html Docs:  http://livedocs.adobe.com/flex/3/html/ Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®
Thank you! Brad Umbaugh [email_address] twitter: bradumbaugh RJ Owen [email_address] twitter: rjowen Copyright 2008 Adobe Systems Incorporated.  All rights reserved.  ®

More Related Content

PPT
Diving in the Flex Data Binding Waters
PPT
Flex data binding pitfalls: 10 common misuses and mistakes
PDF
Flex3 data binding
PDF
Knockoutjs databinding
PDF
Vue.js 101
PPTX
Object identification and its management
PPTX
Bringing the light to the client with KnockoutJS
PPTX
Android data binding
Diving in the Flex Data Binding Waters
Flex data binding pitfalls: 10 common misuses and mistakes
Flex3 data binding
Knockoutjs databinding
Vue.js 101
Object identification and its management
Bringing the light to the client with KnockoutJS
Android data binding

What's hot (7)

PPTX
Data binding
PPSX
Proxy design pattern
PPTX
Proxy Pattern
PPT
Proxy pattern
PPTX
Design pattern proxy介紹 20130805
PPTX
PPT
Silverlight Databinding
Data binding
Proxy design pattern
Proxy Pattern
Proxy pattern
Design pattern proxy介紹 20130805
Silverlight Databinding
Ad

Viewers also liked (20)

PDF
Prototyping Adobe AIR Applications with Fireworks CS4
DOC
Meet the Communication Process by a Journey
PDF
It's not filter failure. It's a discovery deficit.
PPTX
A Data-driven Look at the Realtime Web
PDF
Apple earnings q4-2010
PPT
PDF
But we're already open source! Why would I want to bring my code to Apache?
ZIP
InsideRIA Outlook for 2009
PPT
2 3-2012 Take Control of iCloud
PDF
Twitter Webcast Power Tips, Pt 1
PDF
Visual Experience 360 Flex
PDF
Hoppala at XMediaLab
PPTX
Search Different Understanding Apple's New Search Engine State of Search 2016
PDF
Allister Frost Speaker Biography
PPT
Test Driven Development
PDF
Twitter Webcast Power Tips, Pt 2
PDF
Sharing Apache's Goodness: How We Should be Telling Apache's Story
PDF
Voice+IP Conference Frankfurt, Germany
PDF
Sxsw speaker submission_effectiveui_07252014
PDF
WattzOn Personal Energy Audit
Prototyping Adobe AIR Applications with Fireworks CS4
Meet the Communication Process by a Journey
It's not filter failure. It's a discovery deficit.
A Data-driven Look at the Realtime Web
Apple earnings q4-2010
But we're already open source! Why would I want to bring my code to Apache?
InsideRIA Outlook for 2009
2 3-2012 Take Control of iCloud
Twitter Webcast Power Tips, Pt 1
Visual Experience 360 Flex
Hoppala at XMediaLab
Search Different Understanding Apple's New Search Engine State of Search 2016
Allister Frost Speaker Biography
Test Driven Development
Twitter Webcast Power Tips, Pt 2
Sharing Apache's Goodness: How We Should be Telling Apache's Story
Voice+IP Conference Frankfurt, Germany
Sxsw speaker submission_effectiveui_07252014
WattzOn Personal Energy Audit
Ad

Similar to Flex3 Deep Dive Final (20)

PDF
Flex 3 Deep Dive
PPT
How To Navigate And Extend The Flex Infrastructure
PPT
ActionScript 3.0 Fundamentals
PPTX
Flex Building User Interface Components
PPT
Introduction To Flex
PPTX
MATE: A Flex Framework - "Extreme Makeover"
PDF
杜增强-Flex3组件生命周期
PPT
PDF
PPTX
Exploring Adobe Flex
PPTX
Basics of Flex Components, Skinning
PPT
Adobe Flex Introduction
KEY
Rich Internet Applications and Flex - 4
PPT
Introduction to flex
PPT
2007 Max Presentation - Creating Custom Flex Components
PPT
Eclipse Demo Camp 2010 - UI Bindings - An Introduction
PPT
Flex Book Club Chapter 5
PDF
Data Binding in Silverlight
PDF
Adobe Flex - Developing Rich Internet Application Workshop Day 2
ZIP
A Brief Intro to Adobe Flex
Flex 3 Deep Dive
How To Navigate And Extend The Flex Infrastructure
ActionScript 3.0 Fundamentals
Flex Building User Interface Components
Introduction To Flex
MATE: A Flex Framework - "Extreme Makeover"
杜增强-Flex3组件生命周期
Exploring Adobe Flex
Basics of Flex Components, Skinning
Adobe Flex Introduction
Rich Internet Applications and Flex - 4
Introduction to flex
2007 Max Presentation - Creating Custom Flex Components
Eclipse Demo Camp 2010 - UI Bindings - An Introduction
Flex Book Club Chapter 5
Data Binding in Silverlight
Adobe Flex - Developing Rich Internet Application Workshop Day 2
A Brief Intro to Adobe Flex

More from RJ Owen (7)

PDF
Moral Design (Denver Startup Week)
PDF
Moral designfinal
PDF
Flex4 component lifecycle
PPT
Obey The Rules: Implementing a Rules Engine in Flex
PPT
Flex 4 Overview
PDF
Adobe Flex 3 Component Life Cycle
PDF
Adobe Flex Component Lifecycle
Moral Design (Denver Startup Week)
Moral designfinal
Flex4 component lifecycle
Obey The Rules: Implementing a Rules Engine in Flex
Flex 4 Overview
Adobe Flex 3 Component Life Cycle
Adobe Flex Component Lifecycle

Recently uploaded (20)

PDF
Chapter 5_Foreign Exchange Market in .pdf
DOCX
unit 1 COST ACCOUNTING AND COST SHEET
PDF
Nidhal Samdaie CV - International Business Consultant
PPTX
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
PDF
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
PPTX
Dragon_Fruit_Cultivation_in Nepal ppt.pptx
PPTX
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
DOCX
unit 2 cost accounting- Tender and Quotation & Reconciliation Statement
PPTX
Amazon (Business Studies) management studies
PDF
Training And Development of Employee .pdf
PPT
340036916-American-Literature-Literary-Period-Overview.ppt
PDF
COST SHEET- Tender and Quotation unit 2.pdf
PDF
Reconciliation AND MEMORANDUM RECONCILATION
PPTX
HR Introduction Slide (1).pptx on hr intro
PPTX
ICG2025_ICG 6th steering committee 30-8-24.pptx
PPTX
Principles of Marketing, Industrial, Consumers,
PDF
BsN 7th Sem Course GridNNNNNNNN CCN.pdf
PDF
Unit 1 Cost Accounting - Cost sheet
DOCX
Business Management - unit 1 and 2
DOCX
Euro SEO Services 1st 3 General Updates.docx
Chapter 5_Foreign Exchange Market in .pdf
unit 1 COST ACCOUNTING AND COST SHEET
Nidhal Samdaie CV - International Business Consultant
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
Dragon_Fruit_Cultivation_in Nepal ppt.pptx
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
unit 2 cost accounting- Tender and Quotation & Reconciliation Statement
Amazon (Business Studies) management studies
Training And Development of Employee .pdf
340036916-American-Literature-Literary-Period-Overview.ppt
COST SHEET- Tender and Quotation unit 2.pdf
Reconciliation AND MEMORANDUM RECONCILATION
HR Introduction Slide (1).pptx on hr intro
ICG2025_ICG 6th steering committee 30-8-24.pptx
Principles of Marketing, Industrial, Consumers,
BsN 7th Sem Course GridNNNNNNNN CCN.pdf
Unit 1 Cost Accounting - Cost sheet
Business Management - unit 1 and 2
Euro SEO Services 1st 3 General Updates.docx

Flex3 Deep Dive Final

  • 1. A Deep Dive into the Flex 3 Framework Brad Umbaugh RJ Owen EffectiveUI November 18, 2008 Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 2. Introductions Who are we? Brad Senior Developer at EffectiveUI, builds lots of cool stuff, looks a little like John Stamos. RJ Senior Developer at EffectiveUI, Adobe Community Expert, falls asleep when he drinks wine Who are you? Assumptions: You know some Flex You want to know more Flex You know how to get things done with Flex, but not how to make the most of the Flex Framework Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 3. What will we talk about today? Several topics that help you maximize Flex’s power (grr!!) Things many beginner - intermediate developers don’t know a lot about Data Binding Style manager Collections System Manager For each of these, we’ll discuss: What it is How it affects you Best ways to use it Common mistakes to avoid It’ll start simple, and get deeper as we go Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 4. Copyright 2008 Adobe Systems Incorporated. All rights reserved. Data Binding ®
  • 5. The Problem Copyright 2008 Adobe Systems Incorporated. All rights reserved. Need a way to sync views with changing data ®
  • 6. The Scenario Copyright 2008 Adobe Systems Incorporated. All rights reserved. Scenario: A value object with some text that should be displayed on a label ®
  • 7. Roll-my-own solution I have a VO that contains some text I need to display on the screen Copyright 2008 Adobe Systems Incorporated. All rights reserved. public class BoringVO1 { public var _text : String; } ®
  • 8. Roll-my-own solution How will I know when the text field on this object changes? I’ll have it dispatch events. Copyright 2008 Adobe Systems Incorporated. All rights reserved. [Event(name=”textChanged”), type=”flash.events.Event”] public class BoringVO1 extends EventDispatcher { private var _text : String; public function set text( value : String ) : void { _text = value; this.dispatchEvent( new Event(“textChanged”) ); } } ®
  • 9. Roll-my-own solution In the view, I’ll listen for those events: Copyright 2008 Adobe Systems Incorporated. All rights reserved. public function setMyText() { theLabel.text = value; } <mx:Label id=”theLabel”/> private var _vo : BoringVO1; public function set vo( value : BoringVO1 ) : void { _vo = value; _vo.addEventListener( “textChanged”, this.setMyText ) } ®
  • 10. Roll-my-own solution Copyright 2008 Adobe Systems Incorporated. All rights reserved. Ugh. Annoying. Too much code for so simple a task. ®
  • 11. Flex’s solution: data binding Data binding is a contract between two objects: one promises to dispatch events when its data changes, and another promises to listen to those changes and update itself Got this definition from Michael Labriola’s fantastic data binding talk at 360|Flex San Jose, “Diving in the Data Binding Waters” Contrary to popular belief, it isn’t magic: it’s events! Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 12. Flex’s solution: data binding Mark the object and its property as [Bindable], use curly braces, and away you go. Copyright 2008 Adobe Systems Incorporated. All rights reserved. <mx:Label id=”theLabel” text=”{vo.text}”/> [Bindable] public var vo : BoringVO1; public class BoringVO1 { [Bindable] public var text : String; } The VO! The app! ®
  • 13. The Basic Idea A property of a component changes The property’s component fires off an event indicating that the property changed Other components listen for this event, recognize that a needed value has changed, and update themselves with the new value Bindings also fire once on initialization, so that initial values are set correctly Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 14. MXML Example (with curly braces), binding to a property To bind to a property, simply put a reference to the property in curly braces: <mx:Label text=”{anObject.text}”/> The referenced data must be marked as bindable: give it [Bindable] metadata If it isn’t marked as [Bindable], you’ll get a warning from the compiler... “Data binding will not be able to detect assignments...” ...and the binding won’t work. Copyright 2008 Adobe Systems Incorporated. All rights reserved. A warning! ®
  • 15. Metadata What is it? Metadata is information that tells the compiler how components are used in a Flex application. Various kinds: [ArrayElementType], [DefaultProperty], [Deprecated], [Effect], [Embed]... [Bindable] metadata tells the compiler to generate code to dispatch events when the property or properties marked [Bindable] are changed, so that other objects binding to that data will update accordingly. Why is it needed? Remember all of the event dispatching and listening from the roll-my-own example? The [Bindable] metadata tells the compiler to dispatch all of those events when objects or their properties change. Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 16. Metadata Where should [Bindable] metadata be placed? Before a public class definition Makes all public properties, public getters/setters available as binding sources Before a public, protected, or private property defined as a variable Makes that property available as a data binding source Before a public, protected, or private property defined as a getter/setter Makes that property available as a data binding source Components declared in MXML are automatically set as [Bindable] in the compiler-generated Actionscript, as long as they have an id set Example: DataBinding4.mxml / DataBinding4-interface.as What is the syntax? [Bindable] or [Bindable(event=“eventTypeToWhichInterestedComponentsShouldRespond”)] If no event type is given, by default an event named “propertyChange”, of type PropertyChangeEvent is dispatched Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 17. Metadata Why use a custom event type? It’s more efficient than using the default PropertyChangeEvent More on this later Who dispatches the custom event? When no custom event type is specified: Default PropertyChangeEvent is dispatched automatically Example: DefaultEventFiring.mxml When a custom event type is specified: No PropertyChangeEvents are dispatched Custom event types are not dispatched automatically Must dispatch custom events explicitly Example: CustomEventFiring2.mxml Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 18. MXML Example (with curly braces), binding to a function Functions can be used as a source for data binding Must be marked with appropriate metadata: [Bindable(event=”eventType”)] When do bindings to functions execute? Whenever the event type listed in the [Bindable(event=”eventType”)] metadata is dispatched Example: DataBinding6.mxml Whenever one of the bindable arguments passed in to the function changes Code automatically generated to execute the binding whenever one of the function’s passed-in bindable arguments changes Compiler will throw a warning when non-bindable arguments are passed in to the argument list of a bound function (and the binding won’t work, either) On initialization Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 19. MXML Example (with curly braces), binding to XML data Can bind directly to XML data XML does not dispatch change events when nodes are edited, so views may not update correctly XMLListCollection is the class of choice to use as an XML data provider Provides sorting and filtering methods Ensures views get updated when XML nodes are edited Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 20. MXML Example: using <Binding> tag The MXML <Binding> tag accomplishes the same thing as curly braces Allows you to bind multiple sources to a single destination Can place a concatenated Actionscript expression in curly braces in the source property of a <Binding> tag Example: BindingTag.mxml Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 21. What does the generated code buy you? Brevity Lots of error handling Binding to expressions Compiler generates code to evaluate the expression placed in curly braces when particular events are fired off; makes it very easy to bind to complex expressions <mx:Label text=”{a.toString() + b.toString() + “: “ + (c/d).toString}/> Chains Binding to property chains happens easily, too: <mx:Label text=”{this.childA.propertyB.childC.widgetD.text}”/> When childA, propertyB, childC, or widgetD changes, the label’s text updates appropriately All of the event listeners needed to make this happen are created for you in the generated code All of the properties in the chain must be [Bindable] in order for this to work correctly Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 22. Binding in Actionscript: bindProperty() and bindSetter() Bindings can be created in Actionscript code, too Use mx.binding.utils.BindingUtils Two important static methods on the BindingUtils class bindProperty() sets a destination property when a source property or property chain changes Takes a destination object, a destination property, a source object, and a source property chain (remember to make all elements in the source property chain [Bindable]) You can use bindProperty() to set a property that has a setter bindSetter() calls a handler function() when a source property or property chain changes Takes a handler function, a source object, and a source property chain Since handler functions fire when bindSetter is first called; be sure to check for nulls Handler function receives, as a parameter, the new value of the source’s property chain Both of these functions return a ChangeWatcher object; use this to manipulate the binding after it has been created (change handler function, change objects, etc) Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 23. Common problem: performance in Cairngorm Too many bindable fields on the model doesn’t perform well! Why? Every time one of the properties on the model changes, the model dispatches a PropertyChangeEvent Any component binding to any property on the model listen for PropertyChangeEvents dispatched from the model Examines the event to see which property the PropertyChangeEvent is for; disregards if not relevant If the model has a lot of fields, this is a huge amount of unnecessary work Solution? Custom event types Listening components now only receive the particular event type dispatched for the property in question Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 24. Common problem: two-way binding Problem: two fields should update each other Simple solution: Create two bindings, one in each direction. Flex makes sure that an infinite loop won’t occur MXML solution: TwoWayMXML.mxml Actionscript solution: TwoWayActionscript.mxml There’s a shortcut for this coming in Gumbo (Flex 4)... Curly braces <mx:TextInput id=”firstInput”/> <mx:TextInput id=”secondInput” text=”@{firstInput.text}”/> Binding tags <mx:Binding twoWay=”true” ... Check out the Gumbo spec: http://opensource.adobe.com/wiki/display/flexsdk/Two-way+Data+Binding Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 25. Common problem: making whole objects [Bindable] instead of individual properties Imagine a complex graph, with thousands of data points If each point on that graph is an object (VO), any time any point on the object changes it dispatches a property change event. This can get incredibly expensive really fast when there are lots of objects sitting around in memory. Whenever possible, make single properties [Bindable] instead of entire objects. Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 26. Copyright 2008 Adobe Systems Incorporated. All rights reserved. StyleManager ®
  • 27. StyleManager: Styling 101 “Styles” differ from “Properties” in the way they are set, maintained, and accessed in your application Ways to set styles: In MXML, they look just like properties: <mx:Label text=&quot; woot! WTF FTW! &quot; color=&quot; 0x00ff00 &quot; width=&quot; 100 &quot; /> In Actionscript, they must be set through the style manager: var label : Label = new Label(); label.text = &quot;woot! WTF FTW!&quot; ; label.setStyle( &quot;color&quot; , &quot;0x00ff00&quot; ); Why is it more complex in ActionScript? Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 28. StyleManager: Styling 101 Styles are inheritable Styles must propagate to their children, and their children’s children, and sometimes their children’s children, forever and ever. Styles are like genes! This task requires some management The flex team built a class to do just that, and creatively named it the Style Manager. The StyleManager serves as the storehouse for all of this information and makes it available to other components. Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 29. StyleManager: Styling 101 Every time a style is set, the framework has to keep track of: Any parent styles this over-rides Any children who are affected Flex adds/removes styles through proto chaining Style properties are stored in the proto chains - not as properties on the objects themselves proto chains are outside of the scope of our discussion, but it’s a really interesting topic to learn more about. Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 30. Style Precedence Global, Type, Class, Attribute Copyright 2008 Adobe Systems Incorporated. All rights reserved. Text *Image courtesy Juan Sanchez and Andy McIntosh ®
  • 31. Adding styles to components in AS3 To add styles to individual components, use UIComponent.getStyle and setStyle getStyle is cheap - it just reads the style information setStyle is expensive - it has to traverse the entire style tree and re-calculate inheritance. These methods inherently make use of the StyleManager These should satisfy your styling needs on a component level Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 32. Using StyleManager to manage Assets You can embed assets through the StyleManager Advantages: Avoid cluttering your component code with Embed statements Keep all external resource paths in a single place Manage resources that might be used in more than one part of your app .icons { wrenchIcon : Embed ( 'images/wrench.png' ); searchIcon : Embed ( 'images/search.png' ); loginIcon : Embed ( 'images/login.png' ); } <mx:Button icon=&quot; { StyleManager.getStyleDeclaration( '.icons' ).getStyle( 'wrenchIcon' ) } &quot; label=&quot; Customize &quot; /> Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 33. Using the StyleManager Other things you can do with the StyleManager: Make changes to existing styles Useful for programmatically re-themeing at runtime for a configurator StyleManager.getStyleDeclaration(selector); StyleManager.setStyleDeclaration(selector, CSSSelector, update); Clear existing styles StyleManager.clearStyleDeclaration(selector, update) Define whether your styles influence other components StyleManager.registerParentSizeInvalidatingStyle(styleName:String) StyleManager.registerParentDisplayListInvalidatingStyle(styleName) Register aliases for color names “ blue” instead of 0x0000ff StyleManager.registerColorName(colorName, colorValue); Load styles from a swf at runtime StyleManager.loadStyleDeclarations(...); Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 34. Load style declarations at runtime Uses different CSS files for the different themes Load the style declarations from a pre-compiled swf The core of the functionality: private function changeCSS( panelTitle:String, name:String ): void { StyleManager.loadStyleDeclarations( name, true ); } Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 35. Example: swap styles from a SWF at runtime Copyright 2008 Adobe Systems Incorporated. All rights reserved. Example courtesy of Juan Sanchez and Andy McIntosh ®
  • 36. Example: swap styles from a SWF at runtime Copyright 2008 Adobe Systems Incorporated. All rights reserved. Example courtesy of Juan Sanchez and Andy McIntosh ®
  • 37. Example: clearing and restoring styles Same example as before, but a few new buttons / handlers: Copyright 2008 Adobe Systems Incorporated. All rights reserved. public function unloadRed(): void { StyleManager.unloadStyleDeclarations( 'Red.swf' ); } // Code to restore the default 'Halo' button public function restoreDefaults(): void { StyleManager.setStyleDeclaration( 'Button' , defaultButtonStyle, true ); } private var defaultButtonStyle : CSSStyleDeclaration; public function onComplete(): void { defaultButtonStyle = StyleManager.getStyleDeclaration( 'Button' ); } ... <mx:Button label=&quot; Go Red! &quot; click=&quot;loadRed()&quot; /> <mx:Button label=&quot; Go Blue! &quot; click=&quot;loadBlue()&quot; /> <mx:Button label=&quot; Clear &quot; click=&quot;clearStyles()&quot; /> <mx:Button label=&quot; Restore &quot; click=&quot;restoreDefaults()&quot; /> <mx:Button label=&quot; Unload Red &quot; click=&quot;unloadRed()&quot; /> ®
  • 38. Copyright 2008 Adobe Systems Incorporated. All rights reserved. StyleManager demo: ThemeSwap http://www.scalenine.com/samples/themeSwapper/themeSwap.html ®
  • 39. In case it doesn’t work live: “Obsidian” theme Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 40. In case it doesn’t work live: iTunes 7 Theme Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 41. In case it doesn’t work live: Windows Vista theme Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 42. More info? Creating Visual Experiences with Flex 3.0 , by Juan Sanchez and Andy McIntosh Still valid in Flex 4.0! Copyright 2008 Adobe Systems Incorporated. All rights reserved. ScaleNine! Scale....ten? ®
  • 43. Copyright 2008 Adobe Systems Incorporated. All rights reserved. Collections ®
  • 44. What is a collection? Data comes in many formats Objects Arrays XML There are many different kinds of view components Crossing all of the view components with all of the different types of data representations would yield an unmanageable number of classes Need a common way to use any data as the source for any view component This is where mx.collections.* shines Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 45. Why do we need collections? Collections: Abstract the format of the data from the display component Ensure components are updated when data changes Provide consistent operations to use on data Provide sorted views of data Provide filtered views (Reasons taken from the online flex documentation at www.adobe.com ) Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 46. So, what are collections really? Classes that implement IList, ICollectionView IList is an interface that contains that make it easy to work with linear data ICollectionView is an interface that makes it easy to work with hierarchical data ArrayCollection & XMLListCollection are the main ones you’ll use These actually extend ListCollectionView, which implements IList and ICollectionView Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 47. IList Interface for working with linear data Interesting methods: addItem addItemAt getItemAt getItemIndex removeAll removeItemAt setItemAt Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 48. ICollectionView Interface for sorting, filtering, and interacting with linear and hierarchical data Interesting properties sort filterFunction Interesting methods contains createCursor Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 49. ListCollectionView Implements IList Implements ICollectionView Consequently, components extending ListCollectionView can be used anywhere an IList or an ICollectionView is expected Is the base class for ArrayCollecton, XMListCollection Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 50. ArrayCollection, XMLListCollection The two classes in the Flex framework that inherit from ListCollectionView ArrayCollection Uses an array as its data source Good for linear data XMLListCollection Uses an XMLList as its data source XMLList is a list of one or more XML objects Good for hierarchical data Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 51. Where are collections useful? Various classes can all use collection objects as their data source; these are called “data provider components”: ButtonBar ColorPicker ComboBox DataGrid DateField HorizontalList LinkBar List Menu MenuBar PopUpMenuButton Tree etc. Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 52. Review: why do we need collections? Collections: Abstract the format of the data from the display component Ensure components are updated when data changes Provide consistent operations to use on data Provide sorted views of data Provide filtered views Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 53. 1. Abstract the data format The <mx:TileList> can accept many different types of data sources, including an ArrayCollection and an XMLListCollection The component can swap between different collections without a problem Example: AbstractDataFormat.mxml Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 54. 2. Update views when data changes One of the main reasons to use collections is so that when the data contained by the collection changes, views update accordingly Collections fire off CollectionChange events when their items change; views listen for these events and refresh themselves accordingly When passing in non-collection objects as data providers, you may not see the view update immediately Flex wraps the passed in “raw” objects (e.g., Array or XML) in collection objects; this lets you use your raw data directly. However, changes made directly to those raw objects may not force the views to update Example: UpdateTheViews.mxml Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 55. 3. Consistent data manipulation operations Both ArrayCollection and XMLListCollection inherit from ListCollectionView This makes it easy to edit data in a consistent way, regardless of which type of data is being used for the data provider Square brackets [] (Don’t use these - they’re involved in a Flash Player bug regarding loading sub-applications; use getItemAt() intead) getItemAt() removeItemAt() addItem() Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 56. 4. Sorted views Collections provide a mechanism to sort the view of the data without changing the underlying data itself ListCollectionView’s sort property: type = Sort sort.fields should be an array of SortField objects, which describe how to perform the sort Call refresh() on the collection object after assigning it a sort object Underlying data does not change Example: SortingViews.mxml Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 57. 5. Filtered views Collections also offer an easy way to filter data Simply set the filterFunction property on the collection to a function of the form: function theFilterFunction( item : Object ) : Boolean {} The function should return true on the object if it should be included in the filtered view of the data Example: SortingViews.mxml Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 58. Hierarchical Data Representing hierarchical data in XML is trivial, since XML itself is natively hierarchical: <Foods> <Nuts> <Nut>Peanut</Nut> </Nuts> </Foods> Object graphs can be used, too Example: ObjectHierarchy.mxml Put the child objects in the “children” field of the object Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 59. Cursors Classes used to navigate through collection objects Provide convenient, consistent ways to access data in collections Initialize to the first element in the collection Cursors allow: Movement through data (forward, back) Searching (only if the collection is sorted) Bookmarks Data manipulation (addition, removal) Great for navigating and searching through data They respect sorts (even though the underlying data isn’t actually sorted, cursor will behave like it is) They have an optimized find method Handy for paging through long results sets Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 60. Common Problem: Manipulating a view component immediately after changing the data provider Setting the dataProvider property on a component such as a Tree requires that it validate its properties and layout; it may need to add or remove children based on the changes Attempting to manipulate the view component immediately after setting the dataProvider (i.e., on the next line of code) can cause runtime errors because the component has not yet validated its properties and layout To get around this problem, call validateNow() on the view component immediately after setting the dataProvider This forces the component to validate its properties and layout and redraw itself if necessary Only do this when necessary; there’s a performance hit Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 61. Common Problem: Not seeing expected changes in the view If the objects stored in a collection are not [Bindable], the view will not be able to detect when they have changed In these instances, after updating an item in the collection, call the itemUpdated method on the collection, letting it know that its data has changed Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 62. Copyright 2008 Adobe Systems Incorporated. All rights reserved. SystemManager ®
  • 63. SystemManager: overview “Root” of the Flex swf First class that is instantiated Controls and coordinates the initialization of the application Instantiates and displays the pre-loader Instantiates Application and adds it to the display list Manages layers of children for popups (sorta), cursors, and tooltips Switches focus between top-level items like the above list Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 64. SystemManager: 2 frame swf Flex apps currently publish to a 2 frame SWF 1st frame (small): SystemManager , Preloader, DownloadProgressBar, helper classes. 2nd frame (probably big): The rest of the framework, your application, embedded assets Copyright 2008 Adobe Systems Incorporated. All rights reserved. SystemManager Preloader DownloadProgressBar HelperClasses Flex Framework Application code Embedded Assets Frame 1 Frame 2 RSLs ®
  • 65. SystemManager: 2 frame walkthrough Frame 1 streams in, plays SystemManager is created SystemManager takes over - creates Preloader Preloader tracks the rest of the bytes streaming in, provides updates to SystemManager Once all bytes for frame 2 are streamed in, frame 2 plays Copyright 2008 Adobe Systems Incorporated. All rights reserved. SystemManager Preloader DownloadProgressBar HelperClasses Frame 1 ®
  • 66. SystemManager: 2 frame walkthrough Frame 2 plays SystemManager instantiates Application, sets Application.systemManager to itself Application initializes itself, emits CreationComplete SystemManager adds Application to the DisplayList, hands control over to Application / LayoutManager applicationComplete event is dispatched, and your app is ready to go Copyright 2008 Adobe Systems Incorporated. All rights reserved. Flex Framework Application code Embedded Assets Frame 2 RSLs ®
  • 67. SystemManager: what is it good for? Dispatches browser-resize events Detecting if assets have been embedded Fonts, for example. If the font isn’t embedded, use a different font. SystemManager.embeddedFontList; Displaying your own preloader and... Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 68. SystemManager: what else is it good for? Getting a reference to the root object SystemManager.stage Flash converts have probably spent some time looking for this Monitoring keyboard and mouse activity Manipulate multiple pop-ups, cursors, or tool-tips from their parent Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 69. SystemManager Pitfalls: Multiple Child Lists PopUp windows added through PopUpManager.addPopUp or createPopUp do not go on the SystemManager.popupChildren list by default - they go on the normal Application child list. This list is displayed above the Alert child list and toolTipChildList To add them there, pass the constant PopUpManagerChildList.POPUP as the fourth parameter to the add or create methods on PopUpManager PopUpManager.createPopUp( this , TestPopUp, false , PopUpManagerChildList.POPUP); cursorChildren are on top of everything, then popupChildren, then toolTipChildren, then the regular old application children. Copyright 2008 Adobe Systems Incorporated. All rights reserved. ® application children toolTipChildren popupChildren cursorChildren
  • 70. SystemManager Pitfalls: The Root The system manager tries to own “_root” May manipulate the root object in ways you’re not expecting in Flash This makes flash / flex integration frustrating at times I’m not going to go into this more, but be aware of it Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 71. Resources Michael Labriola’s 2008 360|Flex San Jose talk about Data Binding: “Diving in the Data Binding Waters” (http://www.onflex.org/ted/2008/08/diving-in-data-binding-waters-with.php) Flex 3 Cookbook (Joshua Noble & Todd Anderson; O’Reilly) Creating Visual Experiences in Flex 3.0 (Juan Sanchez and Andy McIntosh; Addison-Wesley) Programming Flex 2 , Programming Flex 3 (Chafic Kazoun, Joey Lott; O’Reilly) Learning Flex 3 (Alaric Cole; O’Reilly) Online Flex documentation API: http://livedocs.adobe.com/flex/3/langref/index.html Docs: http://livedocs.adobe.com/flex/3/html/ Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®
  • 72. Thank you! Brad Umbaugh [email_address] twitter: bradumbaugh RJ Owen [email_address] twitter: rjowen Copyright 2008 Adobe Systems Incorporated. All rights reserved. ®