2010-06-22 78 views
1

有人可以幫助我理解這一點,因爲它在as3中工作,但在flex中沒有那麼多,我真的無法似乎把我的頭弄得一團糟。我可以通過將我的功能更改爲靜態來工作,但我不想這樣做。Flex 4,包和類

好了,所以我第一次創造了一個包

package testPackage 
{ 
public class TestClass 
{ 
    public function TestClass() 
    {  
    } 

    public function traceName(str:String):void 
    { 
     trace(str); 
    }  
} 
} 

,然後我試圖從

import testPackage.TestClass; 

var getClass:TestClass = new TestClass(); 
getClass.traceName("hello"); 

導入包,創建一個類,但我不斷收到錯誤訪問未定義的屬性getClass

回答

2

您最有可能將新的TestClass()語句直接放入<fx:Script>標籤身體。

這在Flex中不起作用。

<fx:Script>標籤應該只包含導入語句,變量&函數的定義。沒有直接運行時代碼。

您需要將您的類初始化代碼放入其中一個flex事件處理函數中。您可以從應用程序的applicationComplete事件處理函數開始。

像這樣

<?xml version="1.0" encoding="utf-8"?> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
       xmlns:s="library://ns.adobe.com/flex/spark" 
       xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="creationCompleteHandler(event)" 
       > 
    <fx:Script> 
     <![CDATA[ 
      import mx.events.FlexEvent; 
      import testPackage.TestClass; 

      // This doesn't work here 
      // var getClass:TestClass = new TestClass(); 
      // getClass.traceName("hello"); 


      protected function creationCompleteHandler(event:FlexEvent):void 
      { 
       // it works here 
       var getClass:TestClass = new TestClass(); 
       getClass.traceName("hello"); 
      } 

     ]]> 
    </fx:Script> 
    <fx:Declarations> 
     <!-- Place non-visual elements (e.g., services, value objects) here --> 
    </fx:Declarations> 
</s:Application>