Dynamic variable names - Actionscript 3
I would like to dynamica开发者_运维百科lly create elements based on the array. I would like to just put the array name and append _panel ...so menu_item_panel will become settings_panel, info_panel,etc. I cannot figure out how to do that?
var menu_items:Array = new Array("settings","info","debug","Feedback");
var menu_items_count:Number = menu_items.length;
var menu_height:Number = c.height / menu_items_count;
var menu_height_int:Number = 0;
for (var i:int=0; i<menu_items_count; i++)
{
var menu_item_panel:Sprite = new Sprite();
menu_item_panel.graphics.beginFill(0x000000, 1);
menu_item_panel.graphics.drawRect(0, menu_height, c.width, menu_height);
menu_item_panel.graphics.endFill();
menu_panel.addChild(menu_item_panel);
menu_panel.addEventListener(MouseEvent.CLICK,menu_panel_click);
menu_height_int = menu_height_int + menu_height;
}
I would recommend you set the name
property of the Sprite
object to the name of the menu item.
menu_item_panel.name = menu_items[i];
Then in your click
handler you check the name
property of event.target
and perform the appropriate action based on that.
Try this
for (var i:int=0; i<menu_items_count; i++)
{
var menu_item_panel:Sprite = new Sprite();
menu_item_panel.graphics.beginFill(0x000000, 1);
menu_item_panel.graphics.drawRect(0, menu_height, c.width, menu_height);
menu_item_panel.graphics.endFill();
menu_panel.addChild(menu_item_panel);
menu_panel.addEventListener(MouseEvent.CLICK, function(){});
menu_height_int = menu_height_int + menu_height;
// Store the new clip in a var
this[menu_items[i]+"_panel"] = menu_item_panel;
}
// get the clips
trace(this.settings_panel);
trace(this.info_panel);
trace(this.debug_panel);
trace(this.Feedback_panel);
Simple:
for (...)
{
//...
menu_item_panel.name = menu_items[i]+"_panel";
menu_panel[menu_item_panel.name] = menu_panel.addChild(menu_item_panel);
//...
}
That's because two things:
// This line set the name of the item to "settings_panel", "info_panel", etc
menu_item_panel.name = menu_items[i]+"_panel";
// This line add menu_item_panel as a child of menu_panel
// and set the property called "settings_panel", "info_panel", etc
// to the right panel
menu_panel[menu_item_panel.name] = menu_panel.addChild(menu_item_panel);
So when you run this line:
menu_panel.settings_panel;
You are obtaining the menu item called "settings_panel"
This type of setting:
object[string] = property;
Works for all objects that are declared dynamic
(MovieClip
and Object
are dynamic
). That's the way to add (dinamically) properties to an object in run-time.
Why not make a class and extend the sprite class then you can make it as dynamic as you need.
I ended up adding the following and it appears to work. I'm not sure why I have to put "this" anywhere.
this[menu_items[i]+"_panel"] = menu_item_panel;
menu_panel.addChild(this[menu_items[i]+"_panel"]);
And I can make it visible by saying:
this.settings_panel.visible = false;
精彩评论