【问题标题】:eventDispatcher from a sub class to another classeventDispatcher 从一个子类到另一个类
【发布时间】:2013-02-17 18:35:01
【问题描述】:

我已经为以下问题苦苦挣扎了几个小时,例如,如果您不扩展该类,如何从另一个类调用自定义类。

我的主基类上有一个计时器事件,Base.myTimer.addEventListener(TimerEvent.TIMER, processTime) - 基类

然后我稍后在代码中删除该方法 Base.mytimer.removeEventListener(TimerEvent.TIMER, processTime. - 基类

我有一个按钮(Btn 类),当它完成处理后,我想再次调用该方法,但我无法让它工作,因为该方法在按钮类中不存在,但在 Base 类中,所以闪现显然给了我错误 processTime is not defined。

例如,现在我想从按钮内重新实例化事件监听器,所以我有

Base.myTimer.addEventListener(TimerEvent.TIMER, processTime); 或 this.parent.parent["myTimer"].addEventListener()

myTimer 是 Base 类中的静态 Timer。

如果不是自定义方法,例如 Base.myTimer.dispatchEvent(new TimerEvent(TimerEvent.TIMER)),我可以创建一个正常的 dispatchEvent。

到目前为止,我看到的示例还没有解决我的问题。任何帮助,将不胜感激。

【问题讨论】:

    标签: actionscript-3 air adobe dispatchevent


    【解决方案1】:

    看起来按钮类是基类的子树的一部分。在这种情况下,您只需在单击按钮类时执行 dispatchEvent 即可

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

    在 Base 类中,您必须已经可以访问按钮类,因此您可以说:

    button.addEventListener("AddListenerAgain", addListener);
    

    然后在基类中

    private function addListener(e:Event) : void {
     myTimer.addEventListener(TimerEvent.TIMER, processTime);
    }
    

    在此示例中,我已调度并侦听原始字符串。这不是推荐的做法。您必须阅读如何调度自定义事件才能正确执行。

    【讨论】:

    • 谢谢,试试看是否有效。这是有道理的。
    【解决方案2】:

    您可以将对 Base 类的实例的引用传递到您的 Button 实例中。

    // Button class
    package {
        import Base;
        // Other imports...
    
        public class Button {
            public function Button(base:Base):void {
                // processTime and myTimer must be public.
                // I put this line in the constructor for brevity, but if you stored base 
                // in an instance variable, you could put this anywhere in the button 
                // class.
                Base.myTimer.addEventListener(TimerEvent.TIMER, base.processTime)
            }
        }
    }
    
    // Create button like this. 
    var button:Button = new Button(base);
    
    // Or if button is created inside of Base
    var button:Button = new Button(this);
    

    更好的是在 Base 类中创建两个方法,用于添加和删除侦听器,并将 myTimer 和 processTime 设为私有:

    public class Base {
        public function addTimerListeners():void {
            myTimer.addEventListener(TimerEvent.TIMER, processTime)
        }
    
        public function removeTimerListeners():void {
            myTimer.removeEventListener(TimerEvent.TIMER, processTime)
        }
    }
    

    然后你可以从类外调用这两个方法。这使您的班级的内部工作更加隐藏。如果您决定要将 myTimer 更改为实例变量而不是静态变量,则无需对 Base 类之外的代码进行任何更改。这称为封装,是一种很好的做法。

    【讨论】:

    • 这正是我所需要的,我应该考虑到这一点。将基数作为参数传递。感谢您的精彩回答!
    • 如果你接受这个答案,你介意点击接受按钮吗? :)
    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多