在flex中收听自定义事件

时间:2012-12-29 17:10:18

标签: flex events

我在actionscript中创建了一个自定义属性的自定义事件。我可以使用自定义属性调度自定义事件(在Main.mxml中),但我无法在我的应用程序中的任何其他位置侦听此事件。我正在尝试在自定义组件中收听此事件。

当我调试时,我可以确认使用正确的值正确调度事件。

Main.mxml的片段:

var userid:String = result.charAt(4);
//dispatch a custom event in which we store the userid
var event_userid:MyEvent = new MyEvent(MyEvent.COMPLETE,userid);
dispatchEvent(event_userid);

CustomEvent类:

package ownASClass
{
    {
//http://stackoverflow.com/questions/1729470/attaching-a-property-to-an-event-in-flex-as3
    import flash.events.Event;

    public class MyEvent extends Event
    {

        public static const COMPLETE:String = "MyEventComplete";

        public var myCustomProperty:*;

        public function MyEvent(type:String, prop:*) :void
        {
            super(type,true);
            myCustomProperty = prop;

        }

        //override clone() so your event bubbles correctly
        override public function clone() :Event {

            return new MyEvent(this.type, this.myCustomProperty)

        }
    }
}       

}

我在自定义组件中听这个事件:

//init gets called as: initialize="init();
protected function init():void
        {
            //add evt listener for custom event to get userid
            this.parentApplication.addEventListener(MyEvent.COMPLETE,getUserid);
            //my custom component is part of a viewstack defined in main.mxml
        }

protected function getUserid(event:Event):void
        {
            //do something (but this never gets called)

        }

3 个答案:

答案 0 :(得分:1)

protected function init():void
    {
        //add evt listener for custom event to get userid
        this.parentApplication.addEventListener(MyEvent.COMPLETE,getUserid);
        //my custom component is part of a viewstack defined in main.mxml
    }

请尝试按以下方式更改以上行 -

this.addEventListener(MyEvent.COMPLETE,getUserid);

答案 1 :(得分:0)

事件通常会从子窗口到父窗口到应用程序(main.mxml)“冒泡”链。

http://livedocs.adobe.com/flex/3/html/help.html?content=events_08.html

如果您尝试使用某个事件来发信号通知某个子对象,则需要将其定位到那里并拥有一个已注册的事件监听器。

答案 2 :(得分:0)

使用了解决方法,意识到我并不需要发送自定义事件。 在主应用程序中声明了我的用户标识,并使用以下命令在我的组件中调用它:

public var userid:String = FlexGlobals.topLevelApplication.userid;
相关问题