2011-12-07 65 views
3

我有一個標籤,當你點擊一個按鈕時,從var獲取它的值。該變種已經聲明:Flex:更新一個標籤的文本,這是一個變量

public function clickevent 
{ 
label.text = aVariable; 
} 

現在我知道,如果我有這樣的標籤:

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

和aVariable是空的,LABEL2的文本爲空(它沒有給出一個錯誤,在我的情況下只是「空」)。這是我目前的情況。

我想知道的是,當我稍後將aVariable的值更改爲字符串「hasChanged」時,例如。 label2的文本也應該改爲「hasChanged」,用戶不必按下按鈕或任何東西來進行此更改。如何才能做到這一點?

+1

也許這個答案可以幫助你在正確的方向:http://stackoverflow.com/questions/306896/as3-can-i-detect-change-of-value-of-a-variable-using-addeventlistener –

回答

4

我不是100%肯定我明白你的問題,但如果您的變量聲明爲「綁定」,不管你的腳本改變其值或者一個按鈕,標籤的文本propertie將跟隨,因爲它是綁定。

<?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> 
+0

好的,它工作。有趣的是,由於其他原因我經常綁定變種,但我不知道它也解決了這個問題。然而,我在另一個變種上有同樣的問題,但有點複雜。我很快會添加我的第二部分問題。 - –

+0

我在這裏發佈了更高級的問題(保持組織狀態):http://stackoverflow.com/questions/8423226/update-a-var-which-gets-it-its-value-from-another-component –

1

聲明你的變量與[綁定]標籤,如:

[Bindable] private var aVariable:String; 

現在,每當變量aVariable的值發生變化,它反映在標籤上。

+0

好的,它工作。有趣的是,我經常綁定變種vor其他原因,但我不知道它也解決了這個問題。然而,我在另一個變種上有同樣的問題,但有點複雜。我很快會添加我的第二部分問題。 –

+0

我在這裏發佈了更高級的問題(保持組織狀態):http://stackoverflow.com/questions/8423226/update-a-var-which-gets-it-its-value-from-another-component –

2

這也可能是值得注意的是,宣佈在聲明塊中的任何變量使得它可綁定默認:

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

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

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

這僅僅是在腳本塊聲明的替代品。

+0

尼斯小費,謝謝。 –

+0

我在這裏發佈了更高級的問題(保持組織結構):http://stackoverflow.com/questions/8423226/update-a-var-which-gets-it-its-value-from-another-component –