Kevin Verhoeven
Kevin Verhoeven

Reputation: 189

Flex: Update a label's text, which is a variable

I have a label that get it's value from a var when you click on a button. The var has already been declared:

public function clickevent
{
label.text = aVariable; 
}

Now I know that if i have a label like this:

<s:Label id="label2" text="{aVariable}"/> 

and aVariable is empty, label2's text is Null (it doesn't give an error, just "Null" in my situation). This is my current situation.

What I'd like to know is when I later on change the aVariable's value to a string "hasChanged", for example. The label2's text should also change to "hasChanged" without the user having to push a button or anything to make this change. How can this be done?

Upvotes: 3

Views: 6431

Answers (3)

merv
merv

Reputation: 76750

It may also be of note that declaring any variable in the declarations block makes it Bindable by default:

<fx:Declarations>
  <fx:String id="aVariable" />
</fx:Declarations>

<s:Label text="{aVariable}" />

<s:Button label="Click Me" click="aVariable='Clicked!'" />

This is just an alternative to the declaration in the Script block.

Upvotes: 3

Jivago
Jivago

Reputation: 826

I'm not 100% sure I understand your question but if your variable is declared as "bindable", no matter if your script change its value or a button, your text propertie of the label will follow as it is binded.

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Script>
        <![CDATA[
            [Bindable]
            private var aVariable:String;

            protected function button1_clickHandler(event:MouseEvent):void
            {
                aVariable = "My new value";
            }
        ]]>
    </fx:Script>

    <s:layout>
        <s:VerticalLayout/>
    </s:layout>

    <s:Label text="{aVariable}"/>

    <s:Button label="Click me" click="button1_clickHandler(event)"/>

</s:WindowedApplication>

Upvotes: 5

Angelo
Angelo

Reputation: 1666

Declare your variable with the [Bindable] tag, like:

[Bindable] private var aVariable:String;

Now, whenever the value of the variable aVariable is changed, it is reflected on the label.

Upvotes: 2

Related Questions