如何将事件发送到Actionscript 3中的另一个类?

时间:2014-11-11 04:07:55

标签: actionscript-3 actionscript

我搜索过几个文档但我找不到将事件发送到另一个班级。

我试图这样做。

  1. '主'班级有按钮。
  2. '主''子'课程将跟踪"按钮被点击"单击按钮时
  3. 我可以追溯到主要的'带派遣事件的班级。

    但是' sub'上课是个问题。

    我怎样才能将这样的事件发送到' sub'类?

    主类

    package com
    {
        import flash.events.*;
        import flash.display.MovieClip;
        import com.sub;
    
        public class main extends MovieClip
        {
            public static const BTN_CLICKED:String = "btn_Clicked";
    
            public function main():void
            {
                if (stage) init();
                else addEventListener(Event.ADDED_TO_STAGE, init);
            }
    
            public function init(e:Event = null):void
            {
                var flashVars:Object = {};
    
                removeEventListener(Event.ADDED_TO_STAGE, init);
                if(parent != null && parent.parent != null)
                {
                    flashVars = parent. parent.loaderInfo.parameters;
                }
                else
                {
                    flashVars = this.root.loaderInfo.parameters;
                }
                //entry point
                var subClass:sub = new sub;
                subClass.init();
    
                btn.addEventListener(MouseEvent.CLICK, onClick);
                addEventListener(BTN_CLICKED, onbtnClicked, false, 0, true);
            }
    
            public function onClick(e:MouseEvent)
            {
                dispatchEvent(new Event(BTN_CLICKED));
            }
    
            public function onbtnClicked(e:Event)
            {
                trace("clicked");
            }
        }
    }
    

    子类

    package com
    {
        import flash.events.*;
        import flash.display.MovieClip;
        import com.main;
    
        public class sub extends MovieClip
        {
            public function sub():void
            {
                if (stage) init();
                else addEventListener(Event.ADDED_TO_STAGE, init);
    
            }
    
            public function init(e:Event = null):void
            {
                removeEventListener(Event.ADDED_TO_STAGE, init);
                //entry point
                trace("sub class loaded");
            }
        }
    
    }
    

1 个答案:

答案 0 :(得分:1)

您应该将var subClass:sub重新定位到main旁边的public static const BTN_CLICKED:String = "btn_Clicked";类定义的主要集合。{1}}。然后,您可以subClass.dispatchEvent(...)

public class main extends MovieClip {
    private var subClass:sub;
    public function main() {
        ...
        subClass=new sub();
        addChild(subClass); // not just "init()", it's wrong
        ...
    }
    public function onClick(e:MouseEvent)
    {
        dispatchEvent(new Event(BTN_CLICKED));
        subClass.dispatchEvent(new Event(BTN_CLICKED));
    }
}