I cannot figure out how to access items by their ID if I create them dynamically
In one area of my application I am creating a display that builds itself with actionscript during a loop. (in my actual app there are A LOT of nested children and my function might be looking for any of those children) In that AS I assign each item an ID, but when I try to access that item by it's id it fails. What gives? and how can I accomplish finding a UI component without having to go through knowing all of it's possible parents?
Here's a simplified example of what I'm doing. The button click will fail with an error
ReferenceError: Error #1069: Property myPanel3 not found on Test and there is no default value.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init();">
<mx:Script>
<![CDATA[
import mx.containers.Panel;
private function init():void{
var i:uint = 0;
for(i = 0; i<10; i++){
开发者_运维百科 var loopPanel:Panel = new Panel;
loopPanel.title = i.toString();
loopPanel.id = "myPanel" + i.toString();
myVBox.addChild(loopPanel);
}
}
private function clicked():void{
var tracePanel:Panel = this["myPanel3"];
trace(tracePanel);
}
]]>
</mx:Script>
<mx:VBox id="myVBox" x="10" y="10" width="500"/>
<mx:Button id="myBtn" x="518" y="8" label="Click Me" click="clicked();"/>
</mx:Application>
Try this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init();">
<mx:Script>
<![CDATA[
import mx.containers.Panel;
private function init():void{
var i:uint = 0;
for(i = 0; i<10; i++){
var loopPanel:Panel = new Panel;
loopPanel.title = i.toString();
loopPanel.name = "myPanel" + i.toString();
myVBox.addChild(loopPanel);
}
}
private function clicked():void{
var tracePanel:DisplayObject = myVBox.getChildByName("myPanel3");
trace(tracePanel.name);
}
]]>
</mx:Script>
<mx:VBox id="myVBox" x="10" y="10" width="500"/>
<mx:Button id="myBtn" x="518" y="8" label="Click Me" click="clicked();"/>
Changes on two lines:
loopPanel.name = "myPanel" + i.toString();
and
var tracePanel:DisplayObject = myVBox.getChildByName("myPanel3");
Nesting - you should probably create a dictionary (eg. assocative array with "name" - "object reference" pairs) of your custom objects if you need to access them without searching in subcomponents.
精彩评论