2012-12-29 94 views
0

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

当我调试时,我可以确认事件得到正确调度与正确的值。

片段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); 

自定义事件类:

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) 

     } 
+0

你尝试使用creationComplete =“的init() “而不是?我认为当初始化事件被触发时,this.parentApplication可能不存在(所以侦听器永远不会添加任何东西) – 2012-12-29 19:45:20

回答

0

对此使用了一种解决方法,意识到我并不需要派遣自定义事件。 宣布我的主要应用的用户ID和一个名为它在我的组件:

public var userid:String = FlexGlobals.topLevelApplication.userid; 
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);