据我所知,该主题对您并不太适用,除非您实际上是在运行时加载 swf 并尝试侦听它们之间的事件。我还建议不要在显示列表中使用层次结构来收集参考资料,除非层次结构本身确实很重要。例如,这个菜单可能会在关闭时从其父容器中删除,或者需要将一个 displayObject 添加到它所在的同一个容器中,而不关心容器是什么。使用层次结构会强制您为引用维护该层次结构,这有时会使对不断增长的应用程序进行更改变得困难。以下是您可能正在寻找的不使用显示列表来收集参考的示例:
public class Main extends Sprite
{
private var menu:SubMenu;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
menu = new SubMenu(this);
addChild(menu) //This is not neccessary for them to communicate
dispatchEvent(new Event(Event.CHANGE));
}
}
public class SubMenu extends Sprite
{
private var mainMenu:IEventDispatcher; //This could be typed as Main instead of IEventDispatcher if needed.
//Sprites are however IEventDispatchers
public function SubMenu(mainMenu:IEventDispatcher)
{
this.mainMenu = mainMenu;
mainMenu.addEventListener(Event.CHANGE, switchItem, false, 0, true);
}
private function switchItem(event:Event):void
{
trace("Parent_Changed")
}
}
下面是一个使用显示列表层次结构的示例(我不推荐它):
public class Main extends Sprite
{
private var menu:SubMenu;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
menu = new SubMenu();
addChild(menu) //This is neccessary, and the menu cannot be added to a different parent
dispatchEvent(new Event(Event.CHANGE));
}
}
public class SubMenu extends Sprite
{
public function SubMenu()
{
//Neccessary because submenu will not have a parent when its first instantiated.
//When its on the stage then you can have it grab its parent and add a listener.
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(event:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//Parents available
parent.addEventListener(Event.CHANGE, switchItem, false, 0, true);
}
private function switchItem(event:Event):void
{
trace("Parent_Changed")
}
}