UIComponent base class not working - apache-flex

I have a BaseComponentClass that I am using as the class that all my custom components extend.
For some reason, none of my custom components show up at runtime. I am not getting any compile or runtime errors either.
I am implementing all the protected UIComponent methods.
My code looks like this:
public class BaseComponentClass extends UIComponent
{
public function BaseComponentClass()
{
super();
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
}
override protected function createChildren():void
{
super.createChildren();
for (var i:uint=0; i < super.numChildren; i++)
{
var childObj:DisplayObject = super.getChildAt(i);
addChild(childObj);
}
}
override protected function commitProperties():void
{
super.commitProperties();
}
override protected function measure():void
{
super.measure();
}
}
Then I use it as the Base class in my mxml custom components somewhat like this:
<local:BaseComponentClass xmlns:local="local.com.*" xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Button id="btn" label="My Button" />
</local:BaseComponentClass>
The Button never shows up at runtime.

Apparently you want to add child objects to your BaseComponent.
Why don't you inherit from a class that supports this functionality, such as Box or Canvas?

Did you try to set a width and height to that component?
As default, UIComponent width and height are set to 0.
you can see the default values documentation here, and change it accordingly on your base component:
http://livedocs.adobe.com/flex/3/langref/mx/core/UIComponent.html
Good luck!

I'm not sure of the best practices, so do research this before implementing it, but if it were me I would create an array property (children is available from uicomponent), then somewhere in the class use the defaultProperty metadata tag ( [DefaultProperty("children")] ).
If you were to debug your code and put a breakpoint in the for loop, you would never hit the addChild code. infact, goto definition (f3) of createChildren (uiComponent.createChildren) and you will find it empty. You have to explicitly call addChild in the default property setter that you create. Your better bet, if you're always going to use this component as a container-like class, is to just extend Container. F3 down into those classes to get a feel for best practices.

Related

Custom Composite Control not rendering correctly for only 0.5-1 sec after being added back into a VGROUP

I am moving away from MXML and have built a custom component control within ActionScript.
I have the control displaying correctly. The problem comes after I remove it from the display list and add it back in again with the .addElement(control) method.
Here is the code that adds it back in again.
private function displayParameters(parameters:ArrayCollection):void{
for(var index:int = 0; index<parameters.length; index++){
if(parameters[index] is ReportControl){
var control:ReportControl = parameters[index] as ReportControl;
control.percentWidth = 100;
vgParameters.addElement(control);
}
}
}
ReportControl is the base class for comboBoxMultiSelect which is shown below. There is nothing graphically special about ReportControl, it only serves as a programmatic interface for its concrete implementations (polymorphic).
public class comboBoxMultiSelect extends ReportControl{
[Embed("../Assets/Icons/plus-16.png")]
private var plusIcon:Class;
[Embed("../Assets/Icons/minus-16.png")]
private var minusIcon:Class;
private var expanded:Boolean = false;
private var buttonIconChanged:Boolean = false;
private var _drp:ComboBox;
private var _btnMultiple:Button;
private var _horizontalGroup:HGroup;
private var _multiSelector:ReportGridSelector;
private var _multiSelection:Boolean = true;
private var bMultiSelectionChanged:Boolean = false;
public function ToggleExpanded():void{
expanded = !_expanded;
buttonIconChanged = true;
invalidateSize();
invalidateProperties();
invalidateDisplayList();
}
public function comboBoxMultiSelect(){
super();
}
override protected function createChildren():void{
super.createChildren();
if(!_horizontalGroup){
_horizontalGroup = new HGroup();
_horizontalGroup.gap = 0;
_horizontalGroup.percentWidth = 100;
_horizontalGroup.height = ReportControl.SIZE_DEFAULT_HEIGHT;
addChild(_horizontalGroup);
}
if(!_drp){
_drp = new ComboBox();
_drp.text = GuiText;
_drp.percentWidth = 100;
_drp.height = ReportControl.SIZE_DEFAULT_HEIGHT;
_horizontalGroup.addElement(_drp);
}
if(!_btnMultiple && _multiSelection){
_btnMultiple = new Button;
_btnMultiple.setStyle("icon", plusIcon);
_btnMultiple.width = 20;
_btnMultiple.height = ReportControl.SIZE_DEFAULT_HEIGHT;
_btnMultiple.visible = true;
_btnMultiple.addEventListener(MouseEvent.CLICK,
function(event:MouseEvent):void{
ToggleExpanded();
});
_horizontalGroup.addElement(_btnMultiple);
}
}
override protected function commitProperties():void{
super.commitProperties();
if(buttonIconChanged){
if(_expanded==true){
_btnMultiple.setStyle("icon", minusIcon);
}
else{
_btnMultiple.setStyle("icon", plusIcon);
}
buttonIconChanged = false;
}
}
override protected function updateDisplayList(unscaledWidth:Number,
unscaledHeight:Number):void{
super.updateDisplayList(unscaledWidth, unscaledHeight);
_horizontalGroup.width = unscaledWidth;
_horizontalGroup.height = unscaledHeight;
}
override protected function measure():void{
super.measure();
measuredMinWidth = measuredWidth = ReportControl.SIZE_DEFAULT_WIDTH;
//minimum size //default size
if(_expanded==true)
measuredMinHeight= measuredHeight = 200;
else
measuredMinHeight= measuredHeight =
ReportControl.SIZE_DEFAULT_HEIGHT;
}
}
When I add the control back in using vgParameters.addElement(control), the comboBoxMultiSelect is not rendering properly. The plusIcon inside the button _btnMultiple is not postioned correctly at first, but then quickly corrects itself about 0.5-1 secs later.
I pretty sure the problem lies within comboBoxMultiSelect, just not sure how to force the icon to stay in the same place.
This is highly annoying after all my hard work, anyone have ideas as to what I am doing wrong?
Thanks :)
UPDATE -----> Here is the ReportControl code
[Event (name= "controlChanged", type="Reporting.ReportControls.ReportControlEvent")]
[Event (name= "controlIsNowValid", type="Reporting.ReportControls.ReportControlEvent")]
public class ReportControl extends UIComponent
{
private var _guiText:String;
private var _amfPHPArgumentName:String;
private var _reportResult:ReportResult;
private var _sequence:int;
private var _reportId:int;
private var _controlConfiguration:ReportParameterVO;
private var _isValid:Boolean = false;
internal var _selection:Object;
/**
* SIZE_DEFAULT_HEIGHT = 22
*/
internal static const SIZE_DEFAULT_HEIGHT:int = 22;
/**
* SIZE_DEFAULT_WIDTH = 150
*/
internal static const SIZE_DEFAULT_WIDTH:int = 150;
public function get ControlConfiguration():ReportParameterVO{
return _controlConfiguration;
}
public function set ControlConfiguration(value:ReportParameterVO):void{
_controlConfiguration = value;
_guiText = (value ? value.GuiText:"");
_amfPHPArgumentName = (value ? value.AMFPHP_ArgumentName: "");
_sequence = (value ? value.Sequence : null);
_reportId = (value ? value.ReportId : null);
}
public function get IsValid():Boolean{
return _isValid;
}
public function get ReportID():int{
return _reportId;
}
public function get Sequence():int{
return _sequence;
}
public function get ControlRepResult():ReportResult{
return _reportResult;
}
public function set ControlRepResult(value:ReportResult):void{
_reportResult = value;
}
internal function set Selection(value:Object):void{
_selection = value;
}
internal function get Selection():Object{
return _selection;
}
public function get ParameterSelection():Object{
return _selection;
}
public function get GuiText():String{
return _guiText;
}
public function get AmfPHPArgumentName():String{
return _amfPHPArgumentName;
}
public function ReportControl(){
//TODO: implement function
super();
}
public function dispatchControlChanged():void{
this.dispatchEvent(new ReportControlEvent(ReportControlEvent.CONTROL_CHANGED, this, true));
}
public function dispatchControlIsNowValid():void{
this.dispatchEvent(new ReportControlEvent(ReportControlEvent.CONTROL_IS_NOW_VALID, this, true));
}
public function addSelfToValueObject(valueObject:Object):Object{
valueObject[AmfPHPArgumentName] = _selection;
return valueObject;
}
}
I'll try to give you an example of what I mean with the Spark skinning architecture we've discussed in the comments above. It's not directly an answer to your question, but I thought you might find it interesting. I will have to make it somewhat simpler than your component for brevity's sake and because you seem to have stripped out some of the code for your question so I can't know exactly what it's supposed to do.
This will be a component that will let you toggle between a normal and an expanded state through the click of a Button. First we'll create the skin class. Normally you'd create the host component first, but it'll be easier to explain this way.
<!-- my.skins.ComboBoxMultiSelectSkin -->
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
height.normal="25" height.expanded="200">
<fx:Metadata>
[HostComponent("my.components.ComboBoxMultiSelect")]
</fx:Metadata>
<s:states>
<s:State name="normal" />
<s:State name="expanded" />
</s:states>
<s:layout>
<s:HorizontalLayout gap="0" />
</s:layout>
<s:ComboBox id="comboBox" width="100%" />
<s:Button id="toggleButton" width="20"
icon.normal="#Embed('../Assets/Icons/plus-16.png')"
icon.expanded="#Embed('../Assets/Icons/minus-16.png')"/>
</s:Skin>
Thus we've set up completely how your component will look and how it will lay out. Do you feel your headaches dissipating? I for one find this quite elegant. We have the two states and the height of the component will adjust to the currently selected state as will the icon of the Button. How and when the state is toggled is component behaviour and will be defined in the host component.
Now let's create that host component in plain ActionScript. For this we'll extend SkinnableComponent (note that it could also extend your ReportControl if that would extend SkinnableComponent instead of UIComponent).
[SkinState("normal")]
[SkinState("expanded")]
public class ComboBoxMultiSelect extends SkinnableComponent {
[SkinPart(required="true")]
public var toggleButton:IEventDispatcher;
[SkinPart(required="true")]
public var comboBox:ComboBox;
private var expanded:Boolean;
override protected function partAdded(partName:String, instance:Object):void {
super.partAdded(partName, instance);
switch (instance) {
case toggleButton:
toggleButton.addEventListener(MouseEvent.CLICK, handleToggleButtonClick);
break;
case comboBox:
comboBox.addEventListener(IndexChangeEvent.CHANGE, handleComboSelection);
break;
}
}
private function handleToggleButtonClick(event:MouseEvent):void {
toggleExpanded();
}
private function handleComboSelection(event:IndexChangeEvent):void {
//handle comboBox selection
}
protected function toggleExpanded():void {
expanded = !expanded;
invalidateSkinState();
}
override protected function getCurrentSkinState():String {
return expanded ? "expanded" : "normal";
}
}
Allright, there's a lot more going on here.
First look at the SkinState metadata declarations: when a skin class is assigned to the component, the compiler will check whether that skin has the required states implemented.
Then the SkinPart declarations: the name of the property on the host component must exactly match the id of the tag in the skin class. As required is set to true the compiler will check whether these components do really exist in the skin. If you want optional skin parts, you set it to false.
Note that the type of toggleButton is IEventDispatcher: from the host component's point of view, all toggleButton has to do, is dispatching CLICK events. This means that we could now create a skin with <s:Image id="toggleButton" source="..." /> and the whole thing would keep working the same way. See how powerful this is?
Because the skinpart properties are not assigned immediately, we override the partAdded() method which will be executed whenever a component becomes available. In most cases this is the place where you hook up your event listeners.
In the toggleExpanded() method, we toggle the boolean just like the component in your question, however we only invalidate the skin state. This will cause the skin to call the getCurrentSkinState() method and update its state to whatever value is returned.
Et voilà! You have a working component with the behaviour nicely separated into an actionscript class and you didn't have to worry about the layout intricacies. And if you ever wish to create a component with the same behaviour, but it should expand horizontally instead of vertically: just create a new skin that adjusts the width instead of the height and assign that to the same host component.
Oh wait! I nearly forgot to tell you how to assign the skin to the components. You can do it either inline:
<c:ComboBoxMultiSelect skinClass="my.skins.ComboBoxMultiSelectSkin" />
or through styling:
#namespace c "my.components.*";
c|ComboBoxMultiSelect {
skinClass: ClassReference("my.skins.ComboBoxMultiSelectSkin")
}
One thing that stands out is in your implementation of updateDisplayList(). As you know, this is where your component should size and position it's child objects (and/or do any programatic drawing).
But rather than set the child object's width/height directly, you should use one of the Flex lifecycle methods: setActualSize() or setLayoutBoundsSize(). Use setLayoutBoundsSize() with spark components.
When you set a Flex component's width/height, the component will invalidate itself so that on the next update cycle it can be re-rendered. But since you are trying to render the component in updateDisplayList() you should be careful to not invalidate your child objects inside this method.
The setActualSize() and setLayoutBoundsSize() methods set the width/height on a Flex component, but do not invalidate the component.
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
_horizontalGroup.setLayoutBoundsSize(unscaledWidth, unscaledHeight);
// if you wanted to position objects, you would set their x/y coordinates
// here with the move() or setLayoutBoundsPosition() methods
}
Note, it looks like some child objects are being sized in createChildren() as well ... and it's not really clear what the base Flex component is in this case (what class does ReportControl extend?
Doing it this way may get rid of that rendering glitch. It will most certainly execute less code than if you set width/height properties directly.
[Edit]
It may be an interaction with the HGroup which is kind of unnecessary in this component. While I think making components this way is fun, it can be more tedious... which is why #RIAStar is wisely pointing out another approach.
Some further ideas, if you want to continue down this path:
1) Take a look at the sizing you are doing in createChildren() - for example, the HGroup is given a percentWidth, but in updateDisplayList() it is given a fixed width (this may be a red herring, but I would not set the percentWidth).
2) You might be able to trick the component into validating itself after you remove it or before you re-add it. A hacky hunch that may be a waste of time.
3) Remove the 'HGroup' from your component. It's kind of unnecessary: the layout requirements are simple enough to do w/a few lines of Actionscript. Your mileage will vary as the layout requirements get more complex!
In createChildren() add the combo box and button directly to the UIComponent. Then size and position them in updateDisplayList(), something like this:
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var padding:Number = 10;
var gap:Number = 0;
// make the ComboBox consume all of the width execpt for 20px and gap + padding
var availableWidth:Number = unscaledWidth - 20 - gap - (2*padding);
_drp.setLayoutBoundsSize(availableWidth, unscaledHeight); // combo box 100% width
_btnMultiple.setLayoutBoundsSize(20, unscaledHeight); // button is 20px wide
// now position them ...
// probably should not use 0, rather calculate a Y coordinate that centers them
// in the unscaledHeight
_drp.setLayoutBoundsPosition(padding, 0);
_btnMultiple.setLayoutBoundsPosition(unscaledWidth - padding - 20, 0);
}
Thank you both so much for your answers! The consideration and attention to detail in explaining the concepts is awesome! Très bien!
#RIAstar However due to the amount of code already in place, changing my architecture (separating visual element from behavioural) would force to large a re-factor of the code and would cost to much for a feature that hasn't been explicitly requested. (visual representation of the control being able to change at runtime) It certainly is interesting and I will be adding that into a future version.
That said, I think I've been able to find a solution to my problem. I decided to build off of #SunilD.'s suggestion of validating the control before it's added back in. A hack I know, but humans aren't perfect and thus the code aint either. ;-)
When looking at the control, I noticed it was only the button that was having issues with rendering its image. So to test, I added and removed JUST a button instance with an icon, and I saw the same behaviour! (regardless of how comboBoxMultiSelect was implemented) I ALSO noticed that I didn't see the button do this when it was first created. So why not just reconstruct the button when it gets removed from the display list?
I ended up wiring comboBoxMultiSelect to the FlexEvent.REMOVE event, destroy the button reference, create a new one, and add it back in with AddChild(). Below is an explanation of the event.
"Dispatched when the component is removed from a container as a content
child by using the removeChild(), removeChildAt(), removeElement(), or
removeElementAt() method. If the component is removed from the
container as a noncontent child by using the rawChildren.removeChild()
or rawChildren.removeChildAt() method, the event is not dispatched.
This event only dispatched when there are one or more relevant
listeners attached to the dispatching object."
Sure enough, this fixed the icon from displaying incorrectly and explains what happening. For some reason the button is taking more than one render event to apply its style when it's added back in. Anyone else able to replicate this behaviour?
I guess the real question now is "what is the best way to remove and add-back-in a button to the display list, so that its embedded icon is unaffected?"

Flex 4 Skin: Change skin based on parent containers state

I have a custom component ExpandCollapseMenu that extends SkinnableContainer. This component can have state "normal" or "expanded".
Inside this component I have buttons, with different skin based on ExpandCollapseMenu's state.
This works fine when defining the buttons inside ExpandCollapsMenu's skin class:
<s:Group id="contentGroup" top="20" left="10" right="10" bottom="10">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<component:ExpandCollapseMenuButton label="Foo" skinClass.expanded="component.ExpandCollapseMenuButtonExpandedSkin" skinClass.normal="component.ExpandCollapseMenuButtonSkin" />
</s:Group>
But I don't want to define the buttons inside ExpandCollapsMenu's skin class, I want to define them where I use ExpandCollapseMenu. Like this:
<component:ExpandCollapseMenu skinClass="component.ExpandCollapseMenuSkin">
<component:ExpandCollapseMenuButton label="Foo" />
</component:ExpandCollapseMenu>
At this level, I can't reference skinclass.expanded, but I got it working by using CSS like this:
component|ExpandCollapseMenu:expanded component|ExpandCollapseMenuButton {
skinClass: ClassReference("component.ExpandCollapseMenuButtonExpandedSkin");
}
component|ExpandCollapseMenu:normal component|ExpandCollapseMenuButton {
skinClass: ClassReference("component.ExpandCollapseMenuButtonSkin");
}
Is this a good way to change skin based on parent containers state? Or is there a better way?
I recommend you to solve the problem on a ExpandCollapseMenu container level. When ExpandCollapseMenu's state is changed you should iterate over children and set some flag for each of them.
So I suggest to introduce expanded:Boolean flag for ExpandCollapseMenuButton.
The problem occurs if ExpandCollapseMenu can contain other instance's types. In this case we can solve it using the following two ways:
Check components in process of iterating if they are ExpandCollapseMenuButton instances (using is operator).
Introduce simple Expandable interface like the following:
public interface Expandable
{
function set expanded(value:Boolean);
}
and implement this interface by ExpandCollapseMenuButton. So you can use is operator in iterator body more flexible way without ExpandCollapseMenuButton dependency.
So the last part of puzzle is to implement setter in ExpandCollapseMenuButton class and switch skin:
private var expandedDirty:Boolean;
private var _expanded:Boolean;
public function set expanded(value:Boolean)
{
if (value == _expanded)
return;
_expanded = value;
expandedDirty = true;
invalidateProperties();
}
override protected function commitProperties():void
{
super.commitProperties();
if (expandedDirty)
{
if (_expanded)
setStyle("skinClass", ExpandCollapseMenuButtonExpandedSkin);
else
setStyle("skinClass", ExpandCollapseMenuButtonSkin);
expandedDirty = false;
}
}

binding exists property in actionscript

how can i do binding exists property in actionscript e.g. i want image still in middle aplication..in mxml i do this simple as <mx:Image source="image.jpg" x="{this.width/2}"/> ...i don't know how can i do this simple in actionscript without event handlers... i put this code to application_creationCompleteHandler..
something like var image:Image = new Image(); image.source="image.jpg"; image.x=this.width/2; or have i put this to another function?? i can't do e.g. updateComplete event handler and change it there...
thanks
pavel
Check the BindingUtils class and its bindSetter method. You can bind a setter to the "width" property and adjust the x property of your image in that handler.
Considering that as3 is OO language i always start from something like this:
public class App extends Sprite {
public function App() { //constructor
super(); //extends class constructor
loading(); //your function were you set all elements properties
}
}

Giving Flex MXML views their dependencies

I'm used to building applications using pure AS3. I always pass dependencies into the constructor of classes I make, but this method seems to not work out well for Flex MXML views.
It seems like I should define setters on the MXML class, which map to attributes in the tag/class instantiation. But using this method I cannot specify which properties are required and in what order I expect them etc.
What is the preferred method to give a Flex view it's dependencies?
A pattern I've used a couple times was to define a public init() method in the MXML which takes the argument that would normally have gone in the constructor. Then, whatever instantiates that MXML component is responsible for calling init() before using it.
Another way would be to create setters for the properties like you mentioned. In those setters store the values that are passed, then call invalidateProperties(). Then override the commitProperties() method in the MXML, and the first time that's called do your initialization (and maybe throw an exception if the needed properties weren't provided). As long as the user of your class sets all the properties before adding the component to the display list then it will work fine (I don't believe commitProperties() is called until after a component is added to the display list, either by being declared in MXML or by passing it to an addChild() call).
I haven't ever tried that second method (only just thought of it now), but it should work.
You can't force people to use parameters in the constructor, but you can force then to set properties before adding the item to the stage.
How's this:
<mx:HBox
added="{checkProps()}">
<mx:Script>
<![CDATA[
public var prop1:String;
public var prop2:String;
private function checkProps():void
{
if( !( prop1 && prop2 ) )
{
throw new Error( "Prop1 and prop2 must be set before "+
"adding this to the stage" );
}
}
]]>
</mx:Script>
</mx:HBox>
Realistically, if you're interested in forcing people to do something before adding it to the display list, then you're going to have to do something like this anyway.
There are a few things in Flex that you can override or listen to that are really important.
FlexEvent.CREATION_COMPLETE - set an eventListener for this (I usually do it in the constructor but you could do it in MXML as creationComplete attribute) and it acts like your constructor. Use getters and setters to pass through references to your dependencies as MXML attributes and store them locally then inside this handler you will apply them.
override protected function createChildren - this is called when it is time to add display list items to the component. You shouldn't do that during the constructor or creationComplete handlers. It is always tempting to addChild outside of this function but Adobe best practice is only to do so directly in this function.
override protected function updateDisplayList - this is where your drawing logic should happen (if there is any) or positioning/alpha/rotation/etc of children. This will get called if a CSS property changes, a child changes size or position or anything else that the Flex framework thinks may cause you to want to redraw the screen. You can force an updateDisplayList to get called by calling invalidateDisplayList
override protected function commitProperties - this is called when the dataProvider for a class is changed. Any time data within the component means you want to update internal data structures this should be called. You can force this to be called using invalidateProperties.
FlexEvent.ADDED_TO_STAGE - If you need to know when the component is actually added to the stage you can listen for this. In practice I can't remember ever actually using it ...
Always remember to call the super equivalents -- forgetting to do so will often cause the component to fail to appear at all (this happens to me at least 4 or 5 times a project). Also be aware that if you first invalidateProperties and then commitProperties and then invalidateDisplayList and then updateDisplayList you may see some jerkyness ... that is, invalidateDisplayList as soon as you know you'll want a redraw to avoid delay.
Also don't get too invested in Flex 3 since Flex 4 is just around the corner and it is quite a bit different. I have a feeling that much of this will no longer apply in the new component framework (names Spark).
edit a typical class stub:
package
{
import mx.containers.Canvas;
import mx.events.FlexEvent;
public class TestComponent extends Canvas
{
public function TestComponent()
{
super();
addEventListener(FlexEvent.CREATION_COMPLETE, init);
}
// acts as constructor
private function init(event:FlexEvent):void
{
// might as well be clean
removeEventListener(FlexEvent.CREATION_COMPLETE, init);
// do init stuff here
}
override protected function createChildren():void
{
super.createChildren();
// do any addChilds here that are necessary
}
override protected function commitProperties():void
{
super.commitProperties();
// update internal state when data changes
}
override protected function updateDisplayList(w:Number, h:Number):void
{
super.updateDisplayList(w, h);
// do any drawing, positioning, rotation etc.
}
}
}

Flex - Sending a parameter to a custom ItemRenderer?

What I am trying to accomplish to to get financial data in my Flex Datagrid to be color-coded--green if it's positive; red if it's negative. This would be fairly straightforward if the column I want colored was part of the dataProvider. Instead, I am calculating it based on two other columns that are part of the dataProvider. That would still be fairly straightforward because I could just calculate it again in the ItemRenderer, but another part of the calculation is based on the value of a textBox. So, what I think I need to be able to do is send the value of the textBox to the custom ItemRenderer, but since that value is stored in the main MXML Application, I don't know how to access it. Sending it as a parameter seems like the best way, but perhaps there's another.
Here is the current code for my ItemRenderer:
package {
import mx.controls.Label;
import mx.controls.listClasses.*;
public class PriceLabel extends Label {
private const POSITIVE_COLOR:uint = 0x458B00 // Green
private const NEGATIVE_COLOR:uint = 0xFF0000; // Red
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
/* Set the font color based on the item price. */
setStyle("color", (data.AvailableFunding >= 0) ? NEGATIVE_COLOR : POSITIVE_COLOR);
}
}
(data.AvailableFunding doesn't exist)
So does anyone know how I would go about accomplishing this?
You may want to look into ClassFactory from the Flex APIs:
This allows you to set a prototype Object with arbitrary types / values each of which will be passed to the item renderer. From the sample:
var productRenderer:ClassFactory = new ClassFactory(ProductRenderer);
productRenderer.properties = { showProductImage: true };
myList.itemRenderer = productRenderer;
The above code assumed that "ProductRenderer" has a public property called "showProductImage" which will be set with a value of "true."
Ah, so I knew about outerDocument but not parentDocument. I was able to just use parentDocument.*whatever I want from the main App and I can access it as long as it's public.
Example:
setStyle("color", (parentDocument.availableFunding >= 0) ? POSITIVE_COLOR : NEGATIVE_COLOR);
Sweet! :)
You can access the value of the TextBox directly, if you need to, by using the static Application.application object, which is accessible from anywhere in your application.
For example, if you wanted the renderers to be notified when the value of the TextInput control changes, you could do something like this (from within your ItemRenderer, and where myTextInput is the ID of the control defined in your main MXML class):
<mx:Script>
<![CDATA[
import mx.core.Application;
private function creationCompleteHandler(event:Event):void
{
Application.application.myTextInput.addEventListener(TextEvent.TEXT_INPUT, handleTextInput, false, 0, true);
}
private function handleTextInput(event:TextEvent):void
{
if (event.currentTarget.text == "some special value")
{
// Take some action...
}
}
]]>
</mx:Script>
With this approach, each item-renderer object will be notified when the TextInput's text property changes, and you can take appropriate action based on the value of the control at that time. Notice as well that I've set the useWeakReference argument to true in this case, to make sure the listener assignments don't interfere unintentionally with garbage collection. Hope it helps!
There's another technique, which, while it initially feels a little hacky is perhaps less cumbersome and cleaner in actual use.
It involves the little-observed fact that an event dispatch is, of course, synchronous and the event object can be treated as a value object populated by any event handler.
i.e. the ItemRenderer can do something like:
...
var questionEvt:DynamicEvent = new DynamicEvent('answerMeThis', true, true);
if (dispatchEvent(questionEvt))
{
if (questionEvent.answer == "some value")
....
With a corresponding handler somewhere up the view hierarchy above the renderer that has a listener on the event and does something like:
function handleAnswerMeThis(event:DynamicEvent):void
{
event.answer = "another value";
event.dataHelper = new DataHelperThingy();
}
etc.
It need not be a DynamicEvent - I'm just using that for lazy illustrative purposes.
I vote up for cliff.meyers' answer.
Here's another example on setting the properties of an itemRenderer from MXML by building a function that wraps a ClassFactory around the itemRenderer class and that injects the necessary properties.
The static function:
public static function createRendererWithProperties(renderer:Class,
properties:Object ):IFactory {
var factory:ClassFactory = new ClassFactory(renderer);
factory.properties = properties;
return factory;
}
A simple example that adds a Tooltip to each item in a list:
<mx:List dataProvider="{['Foo', 'Bar']}" itemRenderer="{createRendererWithProperties(Label, {toolTip: 'Hello'})}"/>
Reference:
http://cookbooks.adobe.com/post_Setting_the_properties_of_an_itemRenderer_from_MXM-5762.html
You use outerDocument property. Please see the fx:Component reference.
You could create an 'AvailableFunding' static variable in the ItemRenderer and then set it in the parent document.
public class PriceLabel extends Label {
public static var availableFunding:int;
...
...
SetStyle("color", (PriceLabel.availableFunding >= 0) ? NEGATIVE_COLOR : POSITIVE_COLOR);
}
In your parent document, set it when your text box gets updated
PriceLabel.availableFunding = textBox.text;
Obviously it'll be the same value for every ItemRenderer but it looks like that might be what you're doing anyway.
I like to override the set data function of the item renderer to change the renderer when the data provider changes as shown here
When you override the function you could cast the object to your object to make the availableFunding property available.
To access the text box you could try creating a public property and binding the property to the text box in the mxml file:
public var textVar:String;
<mx:itemRenderer>
<mx:Component>
<customrenderer textVar="{txtBox.text}" />
</mx:Component>
</mx:itemRenderer>
Nice ClassFactory Example here
See this example:
itemRenderer="{UIUtils.createRenderer(TextBox,{iconSrc:IconRepository.linechart,headerColor:0xB7D034,subHeaderColor:0xE3007F,textColor:0x75757D})}"

Resources