Flex:为什么我不能处理某些事件?

时间:2020-03-06 14:41:49  来源:igfitidea点击:

在某些情况下,我似乎无法获得接收事件的组件。

[编辑]

为了澄清起见,示例代码只是出于演示目的,我真正要问的是是否存在可以添加侦听器的中心位置,在该位置可以可靠地向任意对象发送事件或者从任意对象可靠地分派事件。

我最终使用parentApplication来分派并接收需要处理的事件。

[/编辑]

如果两个组件的父对象互不相同,或者如下面的示例所示,一个组件是一个弹出窗口,则该事件似乎永远不会到达侦听器(对于无效的调度,请参见方法" popUp"):

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
        layout="absolute" 
        initialize="init()">
<mx:Script>
    <![CDATA[
        import mx.controls.Menu;
        import mx.managers.PopUpManager;

        // Add listeners
        public function init():void
        {
            this.addEventListener("child", handleChild);
            this.addEventListener("stepchild", handleStepchild);
        }

        // Handle the no pop button event
        public function noPop(event:Event):void
        {
            dispatchEvent(new Event("child"));
        }

        // Handle the pop up
        public function popUp(event:Event):void
        {
            var menu:Menu = new Menu();
            var btnMenu:Button = new Button();
            btnMenu.label = "stepchild";
            menu.addChild(btnMenu);
            PopUpManager.addPopUp(menu, this);

            // neither of these work...
            this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]);
            btnMenu.dispatchEvent(new Event("stepchild", true));
        }

        // Event handlers

        public function handleChild(event:Event):void 
        {
            trace("I handled child");
        }

        public function handleStepchild(event:Event):void {
            trace("I handled stepchild");
        }
    ]]>
</mx:Script>

<mx:VBox>
    <mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/>
    <mx:Button label="PopUp" id="btnPop" click="popUp(event)"/>
</mx:VBox>
</mx:Application>

我可以考虑解决方法,但似乎应该有一些中央事件总线...

我想念什么吗?

解决方案

当事件是从btnMenu派发时,我们将侦听器添加到this上。

这应该工作:

dispatchEvent(new Event("stepchild", true));

ps。除非明确要求克服范围问题,否则确实没有理由在所有地方都放置不必要的" this"。在这种情况下,我们可以只保留每个this

以上是正确的。
我们正在从btnMenu分派事件,但是我们没有在btnMenu上监听事件,而是在Application上监听事件。

从应用程序中分派:

dispatchEvent(new Event("stepchild", true));

或者在btnMenu上收听

btnMenu.addEventListener("stepchild",handleStepChild);
btnMenu.dispatchEvent(new Event("stepchild",true));