- <?xml version="1.0"?>
- <!– binding/ASInBraces.mxml –>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
- <mx:Script>
- <![CDATA[
- [Bindable]
- public var inString:String; // 绑定此变量
- public function getNewText(sourceString:String):String {
- return sourceString.toUpperCase();
- }
- ]]>
- </mx:Script>
- <mx:TextInput id="myTI" text="Enter text here"/>
- <mx:Button label="Trigger Binding" click="inString=myTI.text;"/>
- <mx:TextArea text="{getNewText(inString)}"/>
- </mx:Application>
<?xml version="1.0"?> <!– binding/ASInBraces.mxml –> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script> <![CDATA[ [Bindable] public var inString:String; // 绑定此变量 public function getNewText(sourceString:String):String { return sourceString.toUpperCase(); } ]]> </mx:Script> <mx:TextInput id="myTI" text="Enter text here"/> <mx:Button label="Trigger Binding" click="inString=myTI.text;"/> <mx:TextArea text="{getNewText(inString)}"/> </mx:Application>
这里的inString一旦发生改变,会直接触发函数getNewText进行重新执行。
但如果你将函数的参数inString去掉,而直接放到getNewText()中,那么这个函数会在系统初始化的时候执行一次,而起不到绑定的效果。我可是在实际开发中有深刻体会。
2、用<mx:Binding>标签效果和{}一样,只需要指定source和destination两个属性即可,如:
<mx:Binding source="firstName.text" destination="myEmployee.name.first"/>
在<mx:Binding>的source属性中也可以使用{},如下面的例子中,其效果是等同的
- <?xml version="1.0"?>
- <!– binding/ASInBindingTags.mxml –>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
- <mx:Script>
- <![CDATA[
- public function whatDogAte():String {
- return "homework";
- }
- ]]>
- </mx:Script>
- <mx:Binding source="’The dog ate my ‘+ whatDogAte()" destination="field1.text"/>
- <mx:Binding source="{’The dog ate my ‘+ whatDogAte()}" destination="field2.text"/>
- <mx:Binding source="The dog ate my {whatDogAte()}" destination="field3.text"/>
- <mx:TextArea id="field1"/>
- <mx:TextArea id="field2"/>
- <mx:TextArea id="field3"/>
- </mx:Application>
<?xml version="1.0"?> <!– binding/ASInBindingTags.mxml –> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script> <![CDATA[ public function whatDogAte():String { return "homework"; } ]]> </mx:Script> <mx:Binding source="’The dog ate my ‘+ whatDogAte()" destination="field1.text"/> <mx:Binding source="{’The dog ate my ‘+ whatDogAte()}" destination="field2.text"/> <mx:Binding source="The dog ate my {whatDogAte()}" destination="field3.text"/> <mx:TextArea id="field1"/> <mx:TextArea id="field2"/> <mx:TextArea id="field3"/> </mx:Application>
3、在ActionScript中实现绑定
这种方法是使用mx.binding.utils.BindingUtils类来实现的。
如:
BindingUtils.bindProperty(textarea, "text", textinput, "text");
就是直接绑定了两个输入框的text属性,还可以用bindSetter来绑定一个数据源和一个set函数。如:
public function mySetterBinding(event:FlexEvent):void {
var watcherSetter:ChangeWatcher = BindingUtils.bindSetter(setMyString, textInput2, "text");
}
这里就是将textInput2的text属性setter函数和setMyString函数绑定起来,
一旦textInput2的text被修改,那么将会触发setMyString函数。