2009-08-26 31 views
1

爲了說明我的問題。假設以下代碼片段:Flex和Actionscript中的組件名稱和ID,它們來自哪裏?

<?xml version="1.0" encoding="utf-8"?> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

<mx:Script> 
    <![CDATA[ 
     import mx.controls.Button; 

     private function createButton():void 
     { 
      var myButton:Button = new Button(); 
      myButton.label = "Foo"; 
      this.btncontainer.addChild(myButton); 
      trace ("New Button Created [" + myButton.toString() + "]"); 
     }  
    ]]> 
</mx:Script> 

<mx:Button label="Create Button" click="createButton()" /> 
<mx:VBox id="btncontainer" /> 

</mx:Application> 

此腳本的行爲應該很明顯。每次點擊「創建按鈕」按鈕將生成一個新標籤爲「Foo」的按鈕。代碼的功能以及爲什麼它對我來說是有意義的。我的問題是關於控制檯輸出。當我運行在調試模式下的應用,然後點擊「創建按鈕」四次我得到了我的控制檯如下:

New Button Created [main0.btncontainer.Button15] 
New Button Created [main0.btncontainer.Button19] 
New Button Created [main0.btncontainer.Button23] 
New Button Created [main0.btncontainer.Button27] 

我的問題是來自哪裏附加到對象名稱中的數字?例如Button15,19,23,27 ...等等?在背景中是否存在某種保存對象的數組,並且這是一個索引值?它是一種內部計數器嗎?這是某種指針值嗎?在我的測試中,至少,爲什麼在這種情況下,它總是遵循相同的模式15,19,23,27 ...,每次分隔4?

我從概念上理解這裏發生了什麼。一個新的Button對象被派生並分配了內存。每次我點擊「創建按鈕」時,我都會創建一個Button類的新實例並將其作爲子項添加到VBox對象中。我只是很好奇在創建對象時附加到數字的意義或意義是什麼?

回答

4

不要忘記,由於Flex是開源的,您可以在代碼中追蹤這類事情。

我發現了一個名爲NameUtil.displayObjectToString的函數,它似乎負責創建Flex實例的可打印名稱。還有NameUtil.createUniqueName它創建name屬性。

看看代碼,但基本上createUniqueName拆分getQualifiedClassName以獲得沒有包詳細信息的類名稱。 NameUtil有一個靜態計數器,然後將其追加到該名稱的末尾。所以Button15是您的應用程序創建的第15個FlexSprite。

displayObjectToString不是太複雜,除非它通過父母加入「。


有一點要注意的是在UIComponent.as評論:

/** 
* ID of the component. This value becomes the instance name of the object 
* and should not contain any white space or special characters. Each component 
* throughout an application should have a unique id. 
* 
* <p>If your application is going to be tested by third party tools, give each component 
* a meaningful id. Testing tools use ids to represent the control in their scripts and 
* having a meaningful name can make scripts more readable. For example, set the 
* value of a button to submit_button rather than b1 or button1.</p> 
*/ 
public function get id():String 
{ 
    return _id; 
} 

它說:「這個值將作爲對象的實例名稱」,雖然這似乎是真的,我無法找到出其中從id到名稱的分配發生。它可能位於編譯期間由MXML生成的AS3代碼中。

+0

感謝詹姆斯的迴應。 – 2009-08-26 22:09:13

相關問題