So I have a module in flex in which I add a custom component. I also have a class that handles the data I want to show, lets call this class DataHandler.
The DataHandler receives data from the back-end solution and then starts putting the data togheter for my Module and the custom component.
When the data is ready it dispatches an event that my Module catch. I send the new data in to my component.
example code for this in Module:
private function onDataChange(evt:Event=null):void
{
_customComponent.ItemData = _dataHandler.DataProvider;
}
The _customComponent then gets the data :
public function set ItemData(value:ItemDataVO):void
{
_itemdata = value;
}
// _itemdata is a custom class named ItemDataVO
Now in my custom component I just bind the data to my mxml components , for example
<mx:Label
text = "Text: {_itemdata.Text}"
fontFamily = "Hel"
fontSize = "12"
x = "83"
y = "40" />
When I get new data the label automaticly changes.
So far so good. But what I also have in my custom component is i List.
And this is my problem. When I bind the data to the List I do the following:
<mx:List
id = "_list"
dataProvider ="{_itemdata.Collection}"
itemRenderer = "components.renderers.CustomRenderer" />
// this _itemdata.Collection is an ArrayCollection that contains a collection of items based on a custom class.
The binding does not work, and I also get a varning for each item in the list at runtime:
warning: unable to bind to property 'parent' on class 'modules::CustomModule'
( I have also tried, as a workaround, to set the _list's itemrenderer each time the ItemData is set. The new listdata then update but I dont see any visual update in the list. )
Anyone knows how to make this binding work?
Regards Adlertz =)
Have you set the collection property on ItemDataVo to be bindable... something like
package
{
import mx.collections.ArrayCollection;
public class ItemDataVo
{
[Bindable]
public var text : String;
[Bindable]
public var collection : ArrayCollection
public function ItemDataVo()
{
}
}
}
I have made a simplified working example showing binding working on a model similar to yours (although there will obviously be differences) with binding working correctly so long as both the text and collection properties both have the Bindable meta data attached:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:local="*" creationComplete="creationCompleteHandler(event)">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
[Bindable]
protected var itemData : ItemDataVo;
private function creationCompleteHandler(event : FlexEvent) : void
{
generateItemData();
}
protected function generateItemData() : void
{
itemData = new ItemDataVo();
itemData.text = "New Text With Random " + Math.random() * 100;
itemData.collection = generateCollection();
}
protected function generateCollection() : ArrayCollection
{
var arrayCollection : ArrayCollection = new ArrayCollection();
arrayCollection.addItem("New Item With Random " + Math.random() * 100);
arrayCollection.addItem("New Item With Random " + Math.random() * 100);
arrayCollection.addItem("New Item With Random " + Math.random() * 100);
arrayCollection.addItem("New Item With Random " + Math.random() * 100);
arrayCollection.addItem("New Item With Random " + Math.random() * 100);
arrayCollection.addItem("New Item With Random " + Math.random() * 100);
return arrayCollection;
}
private function fullClickHandler(event : MouseEvent) : void
{
generateItemData();
}
private function collectionClickHandler(event : MouseEvent) : void
{
itemData.collection = generateCollection();
}
]]>
</mx:Script>
<mx:VBox width="100%" height="100%">
<mx:VBox>
<mx:Label text="{itemData.text}" />
<mx:List dataProvider="{itemData.collection}" />
</mx:VBox>
<mx:HBox>
<mx:Button label="UPDATE FULL ITEM DATA" click="fullClickHandler(event)"/>
<mx:Button label="UPDATE COLLECTION" click="collectionClickHandler(event)"/>
</mx:HBox>
</mx:VBox>
</mx:Application>
In the past I added my List into my Module and it never gave me any binding problems. But yes it seems very strange that the component in between breaks the binding.
The object stored in the Collection looks like this:
package code.converters.objects
{
public class LineupLI
{
private var _plid:int;
private var _lastname:String;
private var _firstname:String;
private var _shirtnumber:int;
private var _onpitch:Boolean;
private var _distance:Number;
private var _topspeed:Number;
private var _goals:int = 0;
private var _subin:Boolean = false;
private var _subout:Boolean = false;
private var _redcard:Boolean = false ;
private var _yellowcard:Boolean = false;
private var _teamid:int;
private var _teamlongdesc:String;
private var _second_increase:Number;
[Bindable]
public function get OnPitch():Boolean { return _onpitch; }
public function set OnPitch(value:Boolean):void { _onpitch = value; }
[Bindable]
public function get ShirtNumber():int { return _shirtnumber; }
public function set ShirtNumber(value:int):void { _shirtnumber = value; }
[Bindable]
public function get PlId():int { return _plid; }
public function set PlId(value:int):void { _plid = value; }
[Bindable]
public function get FirstName():String { return _firstname; }
public function set FirstName(value:String):void { _firstname = value; }
[Bindable]
public function get LastName():String { return _lastname; }
public function set LastName(value:String):void { _lastname = value; }
[Bindable]
public function get Distance():Number { return _distance; }
public function set Distance(value:Number):void { _distance = value; }
[Bindable]
public function get TopSpeed():Number { return _topspeed; }
public function set TopSpeed(value:Number):void { _topspeed = value; }
[Bindable]
public function get Goals():int { return _goals; }
public function set Goals(value:int):void { _goals = value; }
[Bindable]
public function get SubIn():Boolean { return _subin; }
public function set SubIn(value:Boolean):void { _subin = value; }
[Bindable]
public function get SubOut():Boolean { return _subout; }
public function set SubOut(value:Boolean):void { _subout = value; }
[Bindable]
public function get RedCard():Boolean { return _redcard; }
public function set RedCard(value:Boolean):void { _redcard = value; }
[Bindable]
public function get YellowCard():Boolean { return _yellowcard; }
public function set YellowCard(value:Boolean):void { _yellowcard = value; }
[Bindable]
public function get TeamId():int { return _teamid; }
public function set TeamId(value:int):void { _teamid = value; }
[Bindable]
public function get TeamLongDesc():String { return _teamlongdesc; }
public function set TeamLongDesc(value:String):void { _teamlongdesc = value; }
[Bindable]
public function get SecondIncrease():Number { return _second_increase; }
public function set SecondIncrease(value:Number):void { _second_increase = value; }
}
}
Looks ok to me... i think there could be a couple of problems here. One is the binding not working and the second (as David Hanak stated) being why the warning
warning: unable to bind to property 'parent' on class 'modules::CustomModule'
is being thrown which doesn't seem to relate to any of your objects. I would try to solve the latter first and try and figure out why that is happening. You may find that this fixes the original binding problem.
Related
Currently I have created below class which extends ItemRenderer to add labels for all data points in Line Chart.
package lib
{
public class LineChartLabelRenderer extends UIComponent implements IDataRenderer, IFactory
{
private var _label:Label;
public var solidColor:SolidColor;
public function newInstance():*
{
return new LineChartLabelRenderer();
}
public function LineChartLabelRenderer():void
{
super();
_label = new Label();
addChild(_label);
_label.setStyle("color",0x000000);
_label.setStyle("fontSize",9);
}
private var _chartItem:ChartItem;
public function get data():Object
{
return _chartItem;
}
public function set data(value:Object):void
{
if (_chartItem == value){
return;
}
_chartItem = ChartItem(value);
if(_chartItem != null){
_label.text = LineSeriesItem(_chartItem).yValue.toString();
}
}
override protected function updateDisplayList(unscaledWidth:Number,unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var ls:LineSeries = _chartItem.element as LineSeries;
solidColor = new SolidColor(ls.getStyle("fill"));
_label.setActualSize(_label.getExplicitOrMeasuredWidth(),20);
_label.move(unscaledWidth - _label.getExplicitOrMeasuredWidth() / 2 , this.unscaledHeight - _label.getExplicitOrMeasuredHeight() - 5);
}
}
}
It works well. However since the LineSeries may already be set with other ItemRenderer such as CircleItemRenderer or BoxItemRenderer. I found no where to let me set multiple ItemRender with one LineSeries. I want to know what the best way is to do this.
Thanks to Sunil D.
Finally I create extended ItemRenderer like below
public class LSLabelCircleItemRenderer extends CircleItemRenderer
{
private var _label:Label;
public function LSLabelCircleItemRenderer():void
{
super();
_label = new Label();
}
override protected function updateDisplayList(unscaledWidth:Number,unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if(data != null){
var ls:LineSeries = ChartItem(data).element as LineSeries;
label.text = LineSeriesItem(data).yValue.toString();
skin.parent.addChild(label);
label.setStyle("color",ls.getStyle("fill"));
label.move(skin.x - label.getExplicitOrMeasuredWidth() / 5,skin.y - label.getExplicitOrMeasuredHeight());
}
}
}
I have a Flex Spark dropdownList in which I need to show the Provider FirstName,LastName:
<s:DropDownList id="providerList"
dataProvider="{model.practiceProviderList.practiceProviders}"
labelField="provider.providerName.firstName"/>
But the output shows only [object Object] & [object Object] as there are 2 providers in the DB and does not show the actual values.
The PracticeProviderList.as:
[Bindable]
[RemoteClass(alias="model.PracticeProviderList")]
public class PracticeProviderList extends PracticeProviderListBase {
private var _practiceProviderList:ArrayCollection;
public function get practiceProviders():ArrayCollection
{
return _practiceProviderList;
}
public function set practiceProviders(value:ArrayCollection):void
{
_practiceProviderList = value;
}
The PracticeProvider Object:
public class PracticeProvider {
private var _practiceId:Number;
private var _practiceProviderId:Number;
private var _provider:Provider;
public function set practiceId(value:Number):void {
_practiceId = value;
}
public function get practiceId():Number {
return _practiceId;
}
public function set practiceProviderId(value:Number):void {
_practiceProviderId = value;
}
public function get practiceProviderId():Number {
return _practiceProviderId;
}
public function set provider(value:Provider):void {
_provider = value;
}
public function get provider():Provider {
return _provider;
}
The Provider has providerName:PersonName as one of it's fields & PersonName has firstName:String & lastName:String
I need to show the First Name, Last Name in the dropdownlist. I would appreciate if someone can help in this regard.
Thanks
Harish
The labelField can't concatenate 2 values. Use a labelFunction instead.
If I understand your data model, Something like this:
public function myLabelFunction(item:Object):String{
return item['providerName']['PersonName']['firstName'] + ' ' + item['providerName']['PersonName']['lastName']
}
There are 3 properties (example 1):
[Bindable] public var name:String;
[Bindable] public var email:Number;
[Bindable] public var address:Boolean;
I needed to have 3 helper methods that will be bindable too (example 2):
[Bindable] public var name:String;
[Bindable] public var email:Number;
[Bindable] public var address:Boolean;
public function get nameIsOk():Boolean { return !Strings.isEmpty(name) }
public function get emailIsOk():Boolean { return email == 3 }
public function get addressIsOk():Boolean { return address }
Sure, the code above doesn't work. I made it work by doing this (example 3):
private var _name:String
[Bindable("nameChanged")]
public function get name():String { return _name }
public function set name(v:String):void { _name = v; dispatchEvent(new Event("nameChanged")) }
[Bindable("nameChanged")]
public function get nameIsOk():Boolean { return !Strings.isEmpty(name) }
private var _email:Number
[Bindable("emailChanged")]
public function get email():Number { return _email }
public function set email(v:Number):void { _email = v; dispatchEvent(new Event("emailChanged")) }
[Bindable("emailChanged")]
public function get emailIsOk():Boolean { return email == 3 }
private var _address:Boolean
[Bindable("addressChanged")]
public function get address():Boolean { return _address }
public function set address(v:Boolean):void { _address = v; dispatchEvent(new Event("addressChanged")) }
[Bindable("addressChanged")]
public function get addressIsOk():Boolean { return address }
It does work, but now it is bloated.
Is there a way to reduce this code (example 3) to something smaller (like example 2)?
UPDATE:
Kudos to just_a_dude for nice answer. Here is the final version:
[Bindable] public var name:String;
[Bindable] public var email:Number;
[Bindable] public var address:Boolean;
public function Remixer() {
for each (var f:String in Strings.split("name email address")) {
ChangeWatcher.watch(this, f, onChange)
}
}
private function onChange(e:PropertyChangeEvent):void {
dispatchEvent(new Event(e.property + "Changed"))
}
[Bindable("nameChanged")]
public function get nameIsOk():Boolean { return !Strings.isEmpty(name) }
[Bindable("emailChanged")]
public function get emailIsOk():Boolean { return email == 3 }
[Bindable("addressChanged")]
public function get addressIsOk():Boolean { return address }
Not sure if this is what you're looking for but you can use mx.binding.utils.ChangeWatcher to "watch" for property changes
<?xml version="1.0" encoding="utf-8"?>
<mx:Script>
<![CDATA[
import mx.events.PropertyChangeEvent;
import mx.binding.utils.ChangeWatcher;
[Bindable] public var firstName:String;
[Bindable] public var email:Number;
[Bindable] public var address:Boolean;
private var _watcher:ChangeWatcher;
private function init():void {
ChangeWatcher.watch(this, "firstName", propertyChangeHandler);
ChangeWatcher.watch(this, "email", propertyChangeHandler);
ChangeWatcher.watch(this, "address", propertyChangeHandler);
firstName = "foo";
email = 0;
address = true;
firstName = "bar";
email = 1;
address = false;
}
protected function propertyChangeHandler(event:PropertyChangeEvent):void {
var prop:Object = event.property;
var name:String = prop.toString() + "Changed";
// trace(name); // displays firstNameChanged or emailChanged or addressChanged
dispatchEvent(new Event(name));
}
]]>
</mx:Script>
Let me know if this helps
Cheers
I'm not sure if you need getters, but if not, a nice way to do it, is to just use a single function, and put your bindable strings as arguments.
if you put this in your object:
public function isOk(s:String):Boolean
{
return !Strings.isEmpty(s)
}
You would use it like this:
<mx:CheckBox selected="{yourObject.isOk(yourObject.name)}" />
Generally, if you put a function inside the "{}" with parameters which are bindable, it will be called each time that parameter changes.
I would encapsulate your functionality in a class. Do not repeat yourself :)
private var _product:Product;
[Bindable]
public function get product():Product
{
return _product;
}
public function set product(p:Product):void
{
_product = p;
tn.selectedIndex = 0;
}
<mx:Label text="{product.name}" fontSize="11" fontWeight="bold"/>
How are they getting the product.name value which is inside product class.
package samples.flexstore
{
[Bindable]
public class Product
{
public var productId:int;
public var name:String;
public var description:String;
public var price:Number;
public var image:String;
public var series:String;
public var triband:Boolean;
public var camera:Boolean;
public var video:Boolean;
public var highlight1:String;
public var highlight2:String;
public var qty:int;
public function Product()
{
}
public function fill(obj:Object):void
{
for (var i:String in obj)
{
this[i] = obj[i];
}
}
[Bindable(event="propertyChange")]
public function get featureString():String
{
var str:String = "";
if (triband)
str += "Tri-band ";
if (camera)
str += "Camera ";
if (video)
str += "Video";
return str;
}
}
}
"{product.name}" , the product refers to the getter method!
That's the trick of Flex/ActionScript 3's getter and setter methods
http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=ascomponents_147_08.html
"name" is a public var on the Product class. By definition, "name" will be accessible to any other class. That's what "public" means.
_product is a private instance of the Product class. They are supplying the set product method with a Product value, which sets the _product private variable to an instance of the Product class.
The bracket notation in the text="{product.name}" portion of the above code is shorthand notation for binding the contained variable, in this case the name property of the product instance, to the component property (text). When the set product method is supplied a Product instance, Flex fires events internally that update the components that have that property bound.
Defining Data Models - Flex Quickstarts
I have a collection of objects and each object throws an event every time its value gets updated. Im trying to capture that event by adding a listener to the arraycollection that holds it (see main class) but its not working. Honestly I'm not sure this is the correct approach.
I'm avoiding using Collection.CHANGE because it fells into an infinite recursion ultimately ends in a stack overflow. Any ideas?
[Bindable]
public class NamesVO {
public var steveList:ArrayCollection; // array of SteveVO objects
public function NamesVO() {
steveList = new ArrayCollection();
}
public function rename():void {
for each(var steve:SteveVO in steveList) {
steve.rename();
}
}
}
[Bindable]
public class SteveVO extends EventDispatcher {
public static const VALUE_CHANGED:String = "VALUE_CHANGED";
public var code:String;
public var name:String;
public var _quantity:Number;
public function SteveVO() {
this.code = "";
this.name = "";
_quantity = 0;
}
public function get quantity():Number {
return _quantity;
}
public function set quantity(quantity:Number):void {
_quantity = quantity;
dispatchEvent(new Event(VALUE_CHANGED));
}
public function rename():void {
name = code + " - " + _quantity;
}
}
Main class:
names = new NamesVO();
names.steveList.addEventListener(SteveVO.VALUE_CHANGED, function():void {
names.rename(); // this anon function is not being executed!!
});
var steve:SteveVO = new SteveVO();
names.steveList.addItem(steve);
// names is bound on a datagrid and uses itemeditor for each SteveVO object
The VALUE_CHANGED event is not dispatched by the steveList array Collection so won't be detected by your listener. You could encapsulate the functionality you want inside the NamesVO class by detecting when an item is added to the array collection and adding a listener to the new steveVO object that dispatches the same event from NamesVO. Then just listen for that event in your main class.
Is there a reason to change all the names when one quantity is changed. Would it be better simply to call rename inside the set function of the steveVO class?
To implement the change:
import flash.events.Event;
import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.events.CollectionEventKind;
[Bindable]
public class namesVO
{
public var steveList:ArrayCollection; // array of SteveVO objects
public function namesVO()
{
steveList = new ArrayCollection();
steveList.addEventListener(CollectionEvent.COLLECTION_CHANGE,collChanged);
}
private function collChanged(e:CollectionEvent):void
{
if (e.kind == CollectionEventKind.ADD)
e.items[0].addEventListener(steveVO.VALUE_CHANGED,valueChanged);
}
private function valueChanged(e:Event):void
{
dispatchEvent(new Event(steveVO.VALUE_CHANGED));
}
public function rename():void
{
for each(var steve:steveVO in steveList)
{
steve.rename();
}
}
}
In the main class use:
names = new namesVO();
names.addEventListener(steveVO.VALUE_CHANGED, function():void
{
names.rename();
});
steve = new steveVO();
names.steveList.addItem(steve);
steve.quantity = 12;
Of course this is only an example and only includes the case where one item is added at a time.