Monday, November 17, 2008

Understanding [Bindable]

One of the most tricky and less understood features of flex is Binding.

Sure binding on first sight, is a very simple concept to grasp , but when one tries to apply it practically , one can have himself pulling his hair out.

Read this before you become a virendar sehwag look alike J.


My first doubts on the way [Bindable] arouse when I tried to use the bindable variable on an expression .

I was just wondering if having an expression based on a bindable variable would recompute itself , whenever the variable changed?

I had something like this



private var test:Number = new Number();


private function changeText():void {

            this.test=new Number(nameInput.text);



And I set the value of the bindable variable on button click


<mx:HBox width="100%">


                                   <mx:FormItem label="valueOfTest">

                                                <mx:TextInput id="nameInput" width="100"/>



                                    <mx:FormItem label="Check the Binding effect here">     

                                                <mx:TextInput id="valueAfterChange" text="{test > 1}" width="100"/>




                                                            <mx:Button label="Set" click="changeText()"/>



The value of the second text input did change and the expression was recomputed.

Cool enough. When I removed the [Bindable] metatag the value did not change.That was expected~.

The fact is that the events are not triggered on components that use the variable.Simple.


Now, what if you have an function that is assigned to the text attribute of the second text input?


See this,

I changed the second text inputs definition to


<mx:TextInput id="valueAfterChange" text="{getTextForMe() }" width="100"/>


And I added the function which goes like this

                                    private function getTextForMe():Number {


                                                return test + 10;




My first instinct was that the value would automatically be recomputed , but it did not.

It turns out that the function should be declared as [Bindable] too, so that the property would be recomputed too.



                                    private function getTextForMe():Number {

                                                return test + 10;





Alright so here is the moral of the story.


Have your variables annotated with [Bindable] meta tag whenever the changes to it has to reflect elsewhere.

Changes to variables that are bindable will reflect even if the variable was used in an arithematic expression. I mean any property that uses the bindable variable to compute, its value will be recomputed.

If you are using functions to determine value for  any property that uses the bindable variable , have the function declared as bindable.



Hope it helps I did actually stop you from becoming a virendar sehwag llok alike J

Bookmark and Share

No comments: