design user interface components in flex is just like any other language. This presentation provides some guidelines as to how such components should be design and implemented with performance in mind.
4. What are Components? Owner Events Events Events UI Component subcomponents Data Properties Data Properties Data Properties
5.
6. Composite components that contains other components & the Layout of those other components can be set using one of the Flex layout containers, use MXML.
7. Complex components, such as to modifying the way a container lays out its children, use ActionScript.
10. Component Lifecycle in FLEX Implementing the lifecycle boils down to these methods: Constructor() createChildren() commitProperties() measure() updateDisplayList() Custom events
11. Construction MXML-able components must have zero arg constructors Call super()…or the compiler will do it for you. Good place to attach your own event handlers Try to avoid creating children here…for best performance
12. Construction CONSUMER <local:RandomWalk /> or Varinstance:RandomWalk = newRandomWalk(); COMPONENT public function RandomWalk() { super(); this.addEventListener( MouseEvent.CLICK, clickHandler); }
13. Configuration MXML assigns properties before sub-components are attached and initialized (avoids duplicate code execution). Your properties (get, set functions) need to expect that subcomponents haven’t been created yet. Avoid creating performance bottlenecks: make set functions defer work until validation.
15. Configuration (pattern) CONSUMER … instance.dataProvider = xmlDataSet; instance.width = 600; instance.height = 200; instance.labelText = “hello”; ... Or via binding … labelText=“{hello}” width=“600” … dataprovider=“{xmlDataSet}” COMPONENT private var _labelText:String; private var _labelTextDirty; public function set labelText(value:String):void { If (_labelText != value) { _labelText= value; //BAD _label.text = _labelText; _labelTextDirty = true; invalidateProperties(); //invalidation } }
16.
17. Styles may not be initialized until its ancestors get rooted to the displayList()
18. Parent.addChild(At) calls initialize() method to trigger next phase…you can call this explicitly if necessaryParent addChild (ComponentInstance) Component initialization begins
20. Startup Startup happens in multiple sub-phases: 1. ‘preinitialize’ event is dispatched 2. createChildren method is called, adds sub-components 3. ‘initialize’ event is called – component is fully created 4. First validation pass occurs 5. ‘creationComplete’ event is fired – component is fully commited, measured, and updated.
22. Initialization : createChildren() Creating children here streamlines startup performance Follow the same pattern MXML uses: create, configure, attach. Flex components give subclasses first-crack at defining subcomponents. Don’t forget to call super.createChildren(); Defer creating dynamic and data-driven components to commitProperties();
24. Invalidation Flex imposes a deferred validation model Aggregate changes, defer work until the last possible moment avoid creating performance traps for your consumers Three main invalidation functions: invalidateProperties() invalidateSize() invalidateDisplayList()
25. Invalidation Rules of Thumb: 1. Change values immediately 2. Dispatch events immediately 3. Defer Side-effects and calculations to commitProperties() 4. Defer rendering to updateDisplayList() 5. Be suspicious of rules of Thumb
26. Validation : commitProperties Invoked by the framework immediately before measurement and layout Use it to calculate and commit the effects of changes to properties and underlying data Avoid extra work: Use flags to filter what work needs to be done Proper place to destroy and create dynamic subcomponents based on changes to properties or underlying data.
27. Validation : commitProperties //example override protected function commitProperties():void { if (_cme_datachanged) { _ cme_datachanged = false; //reset flag //data change effects applied here } super.commitProperties(); }
28. Validation : measure Invoked by the framework when a component’s invalidateSize() is called Components calculate their ‘natural’ size based on content and layout rules. Implicitly invoked when component children change size. Don’t count on it: Framework optimizes away unnecessary calls to measure. Quick Tip: start by explicitly sizing your component, and implement this later.
29. Validation : updateDisplayList Invoked by the framework when a component’s invalidateDisplayList() is called The ‘right’ place to do all of your drawing and layout
30. Interaction Properties: Talk to your component Events: Listen to your component Public methods: Only in very specific cases where you can not use properties or events to fulfill the need
31. Interaction: Events Events consist of: Name: A unique (per target) name identifying the type of event Target: the object that dispatched the event Event: An Object containing additional information relevant to the event Handler: the function invoked when the event occurs.
32. Interaction: Events 1. Handling Events Registering, removing, capture, bubble 2. Dispatching Events Flex’s event system is extensible – you can define the events you need to make your component useful. – more on this later Remember that events will bubble up from your sub-components. If you don’t want that to happen, you need to explicitly stop them from propagating.
36. Generalizing Components Three important concepts for generalizing your component Use Properties to generalize the behavior and data Use Skinning and Styling to generalize the look Use Templating to generalize the content.
37. Generalizing Component : Templating Instance properties Properties typed as UIComponent can be set in MXML like any other property. Reparenting allows you to embed passed values into your own display tree. Allows you to define complex components with configurable parts public function set thumbnailView(value:UIComponent) { _thumbnailView = value; addChild(thumbnailView); }
38. Generalizing Component : Templating 2. Item Renderers (Factories) Factories are used to generate multiple child components Data driven components use them to generate renderers for the data Allows you to separate management of the data from displaying the data. Quick Tips: Type your item renderers as IFactory Use the IDataRenderer interface to pass your data to the instances If you have additional data to pass, define a custom interface and test to see if it is supported first.
39. Generalizing Component : Binding Databinding is there to eliminate boilerplate data routing code <mx:Button enabled=“{randomWalk.selectedItem != null}” /> Any property can be the destination of a binding, but the source needs special Support Good rule of thumb: If you think someone might want to bind to it…make it bindable.
40. Generalizing Component: Binding Add [Bindable] to your class: [Bindable] public class RandomWalk extends UIComponent { … Makes all public varsbindable Convenience feature for value objects. Add [Bindable] to your property [Bindable] public varselectedItem:Object; [Bindable] public function get selectedItem():Object { … Wraps the variable or property in an autogenerated get/set Good for simple properties. Roll your own event based bindings: [Bindable(event=“selectedItemChange”)] public function get selectedItem():Object { … dispatchEvent(new Event(“selectedItemChange”)); Works well for read only and derived properties
41. Designing you API: base Class? What Base Class should you extend? UIComponent: Base class for all component and containers Gateway to key flex functionality: styles, Containers, invalidation, etc. Best choice for most components Container (and derivatives): Only use if your customers will think of your component as a container Allows developers to specify children in MXML (but there are other ways) Scrolling, clipping, and chrome management for free Other ‘Leaf’ Components Good for minor enhancements and guaranteeing type compatibility Major Functionality changes run the risk of ‘dangling properties’ Consider using aggregation instead
42. Designing your API: MXML schema Remember, Your API defines your MXML schema Specifically: ClassName -> XML Tags Name Package -> XML Namespace Properties -> XML Attributes Complex Properties -> Child Tags
43. Designing your API: Examples A Few Examples: Choose Properties over Methods Properties can be set from MXML Avoid write-once properties Anything that can be set in MXML can be bound to. Use value objects for complex and multi-valued properties MXML makes object graphs simple <DataGrid> <columns> <DataGridColumncolumnName=“revenue” width=“30” dataField=“revYr” /> <DataGridColumncolumnName=“profit” width=“30” dataField=“profYr” /> </columns> </DataGrid> Use different names for styles, events, and properties.
A common coding practice is to divide an application into functional units, or modules, where each module performs a discrete task. Dividing your application into modules provides you with many benefits, including the following:Ease of development Different developers or development groups can develop and debug modules independently of each other. Reusability You can reuse modules in different applications so that you do not have to duplicate your work.Maintainability By developing your application in discrete modules, you can isolate and debug errors faster than you could if you developed your application in a single file.
Ideally components are placed inside another component or container or document. They fire events and have properties for configuration. As we said earlier components may contain other subcomponents. A point I’m going to stress now and always. Its never recommended to have public methods for components you should always try to introduce events for listening to your component and modify data properties to configure your components. using events and properties allow you to integrate smoothly with the UI model of flex and not create performance issues.
Simple Components: are components that standardize the look and feel for another component by extending it.Composite Components: are components that group one or more components together to control their layout using on of flexlayout container(vBox,hBox,canvas,panel)Complex Components: are “complex” , they modify a container, control behaviour and the way it lays its data Nonvisual Components: such as formatters, validator,
Constructor is called when you instantiate your component.CreateChildren is for instantiating your subcomponents Commitproperties for reading all assign properties … this may be called more than once Measure doing all measurmentsUpdateDisplaylist layout and drawing
Keep in mind , overriding methods is always little bit better than handling events inside a component because IF used correctly they reduce the number rendering cycles
Binding calls the setter of the property
Recommnedations Check if the value actually changed Create a flag to notify the component that the property changed Invalidate the component so it reapplies the property.
Dynamic data driven properties components like those that you don’t need if certain properties are set. Flex calls it when the call to the addChild() ….. That is why it might be called more than once check next slide
Recommendation Check if a subcomponent is already instantiated because createChildren might be called more than when
invalidateProperties() for deferred calculation, child managementinvalidateSize() for changes to the measured size of a componentinvalidateDisplayList() for changes to the appearance of a component