How do I implement data binding in an ActionScript Class? - apache-flex

I am having a problem with binding values in my ActionScript components. I basically want to set the value of a a variable in my component to a value in the model, and have the component variable automatically update when the model value is updated. I think that I just don't fully understand how data binding works in Flex - this is not a problem when using MXML components, but, when using ActionScript classes, the binding does not work.
This is the code I'm using, where the values are not binding:
package
{
public class Type1Lists extends TwoLists
{
public function Type1Lists()
{
super();
super.availableEntities = super.composite.availableType1Entities;
super.selectedEntities = super.composite.selectedType1Entities;
}
}
}
package
{
public class Type2Lists extends TwoLists
{
public function Type2Lists()
{
super();
super.availableEntities = super.composite.availableType2Entities;
super.selectedEntities = super.composite.selectedType2Entities;
}
}
}
/* TwoLists.mxml */
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
public var __model:ModelLocator = ModelLocator.getInstance();
public var composite:Composite =
__model.selectedComposite;
[Bindable]
public var availableEntities:ArrayCollection;
[Bindable]
public var selectedEntities:ArrayCollection;
]]>
</mx:Script>
<mx:List id="availableEntitiesList" dataProvider="{availableEntities}" />
<mx:List id="selectedEntitiesList" dataProvider="{selectedEntities}" />
</mx:HBox>

To use binding by code you should use mx.binding.utils.*
Take a look and the BindingUtils.bindProperty and bindSetter methods.
Also, be careful with manual databinding, it could lead you to memory leaks.
To avoid them, save the ChangeWatcher returned by bindProperty and bindSetter and call watcher's unwatch method when is no more used (i.e, in the dipose or destructor method)

You need to add the [Bindable] tag either to the class itself (making all properties bindable) or the properties you want to be [Bindable]. Marking properties or objects as [Bindable] in your MXML is not sufficient.

To fix this, I simply converted the classes to MXML components, and added a private variable for my ModelLocator.
/* Type1Lists.mxml */
<?xml version="1.0" encoding="utf-8"?>
<TwoLists xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns="*"
availableEntities="{__model.selectedComposite.availableType1Entities}"
selectedEntities="{__model.selectedComposite.selectedType1Entities}">
<mx:Script>
<![CDATA[
import model.ModelLocator;
[Bindable]
private var __model:ModelLocator = ModelLocator.getInstance();
</mx:Script>
</TwoLists>
/* Type2Lists.mxml */
<?xml version="1.0" encoding="utf-8"?>
<TwoLists xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns="*"
availableEntities="{__model.selectedComposite.availableType2Entities}"
selectedEntities="{__model.selectedComposite.selectedType2Entities}">
<mx:Script>
<![CDATA[
import model.ModelLocator;
[Bindable]
private var __model:ModelLocator = ModelLocator.getInstance();
</mx:Script>
</TwoLists>

Related

How can I add a flex component programmatically from within a Papervision Class without using this.parent...?

I have a flex application and a papervision BasicView. I would like to add a new flex UIComponent (such as a button) from within the papervision class. I have posted the full example code below. It works but I would like to be able to accomplish my goal without the "(this.parent.parent as Group).addElement(button);" line.
<!--Application MXML-->
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="50" minHeight="50"
creationComplete="Init()" applicationComplete="Start()">
<fx:Script>
<![CDATA[
import mx.core.UIComponent;
import spark.components.Button;
public var start:QuickStart;
public function Init():void
{
start = new QuickStart();
var uicomp:UIComponent = new UIComponent();
addElement( uicomp );
uicomp.addChild( start );
}
public function Start():void
{
start.GoTime();
}
]]>
</fx:Script>
</s:Application>
//QuickStart.as
package{
import org.papervision3d.view.BasicView;
public class QuickStart extends BasicView
{
public function QuickStart()
{
super(500, 500, true, true);
}
public function GoTime():void
{
var button:Button = new Button;
//this is the offending line
(this.parent.parent as Group).addElement(button);
}
}
}
The version I have does work so please excuse any minor typos.
Logically you would dispatch an event inside your BasicView, listen for it in your main application, and create the button from up there. In a prefect OOP world, every class should be a black box sending events :)

Flex 4: Is there a simple way to extend Spark button?

I created a somewhat custom Spark button by doing the File > New > MXML skin and basing it on spark.components.button. The problem is that I need to add an extra text field to the button component and dynamically change that text...but of course, the property isn't recognized on a Spark Button.
Is there a simple way to add this field to my custom button skin & its property so it can be addressed? If not, is there a simple way to take what I've done and just extend the Spark Button? I can't seem to find any examples that show how to do it without writing it all up in ActionScript.
I'm glad you asked! This is much easier than you'd think so don't be discouraged! ActionScript is pretty easy once you get the hang of it.
First of all, let's define what we want. After reading your question I believe you would like to use your button something like this:
<local:MyCustomButton label="Hello" label2="World!"/>
So let's go over how to make that a reality.
Now, I would highly suggest extending Button with ActionScript, but it is also possible to do in mxml:
//MyCustomButton.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
</s:Button>
Then you can add the SkinParts you need in a <fx:Script>:
<?xml version="1.0" encoding="utf-8"?>
<s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
[SkinPart]
public var secondLabelDisplay:spark.components.Label;
]]>
</fx:Script>
</s:Button>
So now when you make a skin you should include something like the original label, just with a different ID to reflect your new SkinPart:
But wait! What text should our second label show?? Well, we will need to add another property that you can set for each individual instance of the button:
<?xml version="1.0" encoding="utf-8"?>
<s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
[SkinPart]
public var secondLabelDisplay:spark.components.Label;
private var _label2:String;
public function get label2():String
{
return _label2;
}
public function set label2(value:String):void
{
_label2 = value;
}
]]>
</fx:Script>
</s:Button>
Cool, so now we can set label2 when we use our button, but at this point it won't change the label's actual text property. We need to hook up our label2 to our secondLabelDisplay. We do this by calling invalidateProperties when the label2 changes and then change the label in commitProperties (which will be called because of the invalidateProperties() call):
<?xml version="1.0" encoding="utf-8"?>
<s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
[SkinPart]
public var secondLabelDisplay:spark.components.Label;
private var _label2:String;
private var label2Changed:Boolean;
public function get label2():String
{
return _label2;
}
public function set label2(value:String):void
{
_label2 = value;
label2Changed = true;
invalidateProperties();
}
override protected function commitProperties():void
{
super.commitProperties();
if(label2Changed)
{
label2Changed = false;
secondLabelDisplay.text = label2;
}
}
]]>
</fx:Script>
</s:Button>
Lastly, you'll notice that if you change label2 again afte runtime, the label will show the change. But it won't show the change if you set an initial label2 like in our target usage. The Flex team made a special method just for this case, partAdded(). I won't go over too many details about it because there is already a good amount of literature on the subject.
Finally, here's our finished, custom button awaiting a skin to put it to use:
<fx:Script>
<![CDATA[
[SkinPart]
public var secondLabelDisplay:spark.components.Label;
private var _label2:String;
private var label2Changed:Boolean;
public function get label2():String
{
return _label2;
}
public function set label2(value:String):void
{
_label2 = value;
label2Changed = true;
invalidateProperties();
}
override protected function commitProperties():void
{
super.commitProperties();
if(label2Changed)
{
label2Changed = false;
secondLabelDisplay.text = label2;
}
}
override protected function partAdded(partName:String, instance:Object):void
{
if(instance == secondLabelDisplay)
{
secondLabelDisplay.text = _label2;
}
}
]]>
</fx:Script>
Best of luck!

Flex ActionScript Project Error in Object Declaration.(project.mxml file)

I have a Flex ActionScript Application, I need to draw a simple rectangle in stage. I am using
firstapp.mxml and another Class called Book.as;
here is the complete code which i have done.
firstapp.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Script>
<![CDATA[
import com.books.Book;
import flash.display.*;
var n:Book = new Book;
//n.var1 = "Another String";
addChild(n);
]]>
</mx:Script>
</mx:Application>
Book.as
package com.books
{
import flash.display.*;
public class Book extends Sprite
{
public var var1:String = "Test Var";
public var var2:Number = 1000;
public function Book()
{
var b = new Sprite;
b.graphics.beginFill(0xFF0000, 1);
b.graphics.drawRect(0, 0, 500, 200);
b.graphics.endFill();
addChild(b);
}
}
}
I'm new in Flex, So please help me to fix this. I want to show the rectangle.
Since you're trying to add this to a flex component, you probably need to wrap Book in a UIComponent instance:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Script>
<![CDATA[
import com.books.Book;
import flash.display.*;
var n:UIComponent = new UIComponent;
n.addChild(new Book);
addChild(n);
]]>
</mx:Script>
</mx:Application>
Another way of doing this would be to instead make Book inherit UIComponent, like so:
package com.books
{
import flash.display.*;
public class Book extends UIComponent
{
public var var1:String = "Test Var";
public var var2:Number = 1000;
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
graphics.beginFill(0xff0000, 1);
graphics.drawRect(0, 0, 500, 200);
graphics.endfill();
}
}
}
Then you can add Book directly to your application, like so:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:books="com.books.*"
layout="absolute">
<books:Book />
</mx:Application>
Additionally, I suggest you read up on the Flex component architecture. There's some pretty good documentation from Adobe on the subject, but you should be aware that the information is specific to Flex 3 (I noticed you're using Flex 3, hence the link). Even while a lot of the information may still be applicable to Flex 4 (the component lifecycle for instance) there are differences, especially in terms of skinning.
USE var n:Book = new Book(); instead of var n:Book = new Book;
macke showed you good way. But if you want just to show something quickly, change
addChild(b);
to
rawChildren.addChild(b);
Edit: Some clarifications: application is UIComponent, therefore its addChild method needs UIComponent. You want to add Sprite. This can be done with rawChildren.addChild method from application. rawChildren is useful to get Sprites work with UIComponents, but you have to manage sprites yourself (sizes and layout).

Can no longer assign class property values using this["propertyName"] in Flex

Given a dynamic or non-dynamic class like the following:
package {
public class MyClass {
public var myProperty:String;
public var myBooleanProperty:Boolean;
public function MyClass() {}
}
}
Flex 3 allows you to assign a value to myProperty like this:
myClassInstance["myProperty"] = "myValue";
myClassInstance["myBooleanProperty"] = true;
I regularly parse XML to get property names and their values then update correlated classes using this technique; however, Flex 4 no longer allows assigning the boolean property. I don't have a work-around.
If you trace the results:
trace(myClassInstance.myProperty) // Returns "myValue"
trace(myClassInstance.myBooleanProperty) // Returns null
Can someone explain what has changed and how to work-around the issue?
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="application1_creationCompleteHandler(event)"
>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
var c:MyClass = new MyClass();
c["myBooleanProperty"] = true;
trace(c["myBooleanProperty"]);
}
]]>
</fx:Script>
</s:Application>
This outputs "true" with the Flex SDK 4.1.
There may be something else wrong in your code?
You can use Dictionary class instead.
Have you simply tried to do this?
myClassInstance.myBooleanProperty = true;
This is actually the standard way of assigning a value to a public property in AS3.

Flex List ItemRenderer with image loses BitmapData when scrolling

Hi i have a mx:List with a DataProvider. This data Provider is a ArrayCollection if FotoItems
public class FotoItem extends EventDispatcher
{
[Bindable]
public var data:Bitmap;
[Bindable]
public var id:int;
[Bindable]
public var duration:Number;
public function FotoItem(data:Bitmap, id:int, duration:Number, target:IEventDispatcher=null)
{
super(target);
this.data = data;
this.id = id;
this.duration = duration;
}
}
my itemRenderer looks like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" >
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
]]>
</fx:Script>
<s:Label text="index"/>
<mx:Image source="{data.data}" maxHeight="100" maxWidth="100"/>
<s:Label text="Duration: {data.duration}ms"/>
<s:Label text="ID: {data.id}"/>
</mx:VBox>
Now when i am scrolling then all images that leave the screen disappear :(
When i take a look at the arrayCollection every item's BitmapData is null.
Why is this the case?
I changed Datatype of data in Class FotoItem from Bitmap to BitmapData
in the ItemRenderer i do the following:
override public function set data( value:Object ) : void {
super.data = value;
pic.source = new Bitmap(value.image);
}
this works now. No idea why it is not working with bitmaps
I think it might be something with your use of data.data - I believe data is a reserved keyword in Actionscript, and it might be best to name your image property something else, such as data.imageData.
I'm also not sure why you're importing ArrayCollection into your item renderer as you don't appear to be using it in your itemRenderer.
You may also be running into problems with itemRenderer recyling. You may want to override public function set data() and handle setting the individual item properties there instead of relying on binding.
Where are you looking at the arrayCollection to see that the bitmapData is null?

Resources