Flex: binding data to an object
Let's say I have the following:
public class MyObject
{
[Bindable]
public var foo:int = 3;
}
...
[Bindable]
var _obj:MyObject = null;
What's the best way to bind foo so that this binding is updated when _obj is set to a new instance?
I tried:
<mx:Label text="{_obj&&_obj.foo}"/>
But this is ugly. Can I use this somehow
What does the SO :: Flex community think?
source to share
The binding is independent of properties; you can get the benefits of binding to fields or properties.
Sounds like you might have left something behind? The following MXML and AS, for example, work to bind to both a field and a property, once the class and its instance are Bindable:
package
{
[Bindable]
public class MyFoo
{
public var myPublicField:int;
private var _myPrivateField:int;
public function MyFoo()
{
myPublicField = 0;
myPublicProperty = 0;
}
public function get myPublicProperty():int
{
return _myPrivateField;
}
public function set myPublicProperty(value:int):void
{
_myPrivateField = value;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
[Bindable]
private var myFoo:MyFoo;
private function increment():void
{
if (!myFoo)
myFoo = new MyFoo();
myFoo.myPublicField += 1;
myFoo.myPublicProperty += 1;
}
private function replace():void
{
myFoo = new MyFoo();
}
]]>
</mx:Script>
<mx:VBox>
<mx:HBox>
<mx:Label text="Field:" />
<mx:Text text="{myFoo.myPublicField}" />
</mx:HBox>
<mx:HBox>
<mx:Label text="Property:" />
<mx:Text text="{myFoo.myPublicProperty}" />
</mx:HBox>
<mx:Button label="Increment Both Counts" click="increment()" />
<mx:Button label="Replace with New Foo" click="replace()" />
</mx:VBox>
</mx:Application>
By the way, the effect will be the same if you split the field and the Bindable property separately, rather than marking the class that is just shorthand for the same. Also note that myFoo runs null by default, as in your example code (ie the assignment "= null" is redundant).
Does this example help? If not, leave a comment and I'll be back. Hope so!
source to share
Use properties instead of public variables.
// Object
package MyObject
{
public class MyObject
{
private var message:String;
public function set Message(messagein:String):void
{
message = messagein;
return;
}
[Bindable]
public function get Message():String
{
return message;
}
public function MyObject()
{
}
}
}
// Flex that calls it
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="281" height="156">
<mx:Script>
<![CDATA[
import MyObject.MyObject;
[Bindable]
private var o:MyObject = new MyObject();
private function UpdateMessage():void
{
o.Message = TextIn.text;
return;
}
]]>
</mx:Script>
<mx:Label x="31" y="29" text="{o.Message}" width="201" id="TextOut"/>
<mx:TextInput x="31" y="55" id="TextIn"/>
<mx:Button x="31" y="85" label="Button" click="UpdateMessage()"/>
</mx:Application>
source to share