Defining bindings in ActionScript

You typically define a data binding in MXML by using the curly braces ({ }) or the <mx:Binding> tag. You can also define a binding in ActionScript by using the mx.binding.utils.BindingUtils class. This class defines static methods that let you create a binding to a property implemented as a variable, by using the bindProperty() method, or to a property implemented as a setter method, by using the bindSetter() method.

In the following example, you use the bindProperty() method to create a binding between a TextInput control and a TextArea control:

<?xml version="1.0"?>
<!-- binding/BindInAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    initialize="initBinding();">

    <mx:Script>
      <![CDATA[

        import mx.binding.utils.*;

        // Define data binding.
        public function initBinding():void {
          BindingUtils.bindProperty(textarea, "text", textinput, "text");             
        }
      ]]>
    </mx:Script>

    <mx:TextInput id="textinput" text="Hello"/>
    <mx:TextArea id="textarea"/>
    <mx:Button label="Submit" click="textinput.text='Goodbye';"/>
</mx:Application>

The following example uses the bindSetter() method to set up two bindings. As you enter text in the TextInput controls, it is copied to the corresponding TextArea control:

<?xml version="1.0"?>
<!-- binding/BindSetterAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:Script>
        <![CDATA[

            import mx.binding.utils.*;
            import mx.events.FlexEvent;

            // Set method.
            public function setMyString(val:String):void {
                taSetter2.text = val;
            }

            <!-- Event listener to configure binding with a setter. -->
            public function mySetterBindingInline(event:FlexEvent):void {
                var watcherSetter:ChangeWatcher = 
                    BindingUtils.bindSetter(
                        function(v:String):void { 
                            taSetter1.text = v}, tiSetter1, "text");
            }

            <!-- Event listener to configure binding with a setter. -->
            public function mySetterBinding(event:FlexEvent):void {
                var watcherSetter:ChangeWatcher = 
                    BindingUtils.bindSetter(setMyString, tiSetter2, "text");
            }
        ]]>
    </mx:Script>

    <mx:Label text="Bind Setter using inline setter"/>
    <mx:TextInput id="tiSetter1" text="Hello Setter" />
    <mx:TextArea id="taSetter1" 
        initialize="mySetterBindingInline(event);"/>

    <mx:Label text="Bind Setter using setter method"/>
    <mx:TextInput id="tiSetter2" text="Hello Setter" />
    <mx:TextArea id="taSetter2" 
        initialize="mySetterBinding(event);"/>
</mx:Application>

Flex 2.01

Take a survey