如何实现自定义事件?

时间:2011-05-12 14:13:07

标签: actionscript-3 model-view-controller events

如何正确实现自定义事件?我认为以下内容应该可行,但我从未在主模型

中收到CustomEvent.READY
package mvc
{
    import flash.events.Event;
    public dynamic class CustomEvent extends Event
    {
       public static const MY_EVENT:String = "myEvent";
       public static const READY:String = "ready";

    public function CustomEvent(type:String)
    {
        super(type);
    }
}
}

在Model.as中扩展了AbstractModel,它扩展了EventDispatcher

private function initWorld():void {
        _worldModel = new WorldModel();
        _worldModel.addEventListener(CustomEvent.READY, update);
}

然后在WorldModel.as中扩展了扩展EventDispatcher的AbstractModel,我调度了一个事件,但是从不调用update。为什么呢?

dispatchEvent(new Event(CustomEvent.READY));

2 个答案:

答案 0 :(得分:1)

_worldModel.dispatchEvent(new CustomEvent(CustomEvent.READY));

您必须实例化CustomEvent,而不是事件。差异很大。

您还可以使用自定义事件通过调度事件传递其他参数,如果您大量使用CustomEvent,这将非常方便

package com.b99.events 
{
    import flash.events.Event;

    /**
     * ...
     * @author bosworth99
     */
    public class AppEvents extends Event
    {
        public static const APP_READY       :String = "application ready";
        public static const XML_LOADED      :String = "XML has loaded";
        public static const CHANGE_COMPLETE :String = "state change complete";
        public static const PAGE_ADDED      :String = "page content added";
        public static const PAGE_REMOVED    :String = "page content removed";
        public static const LIBRARY_LOADED  :String = "external library loaded";
        public static const IMAGE_LOADED    :String = "external image loaded";
        public static const LOAD_ERROR      :String = "external load failed";

        public var arg:*;

        public function AppEvents(type:String, bubbles:Boolean = false, cancelable:Boolean = false, ...a:*) 
        {
            super(type, bubbles, cancelable);
            arg = a;
        }

        override public function clone():Event 
        {
            return new AppEvents(type, bubbles, cancelable, arg);
        }

    }
}

然后,您可以将任意数量的参数传递给接收函数:

this.dispatchEvent(new AppEvents(AppEvents.LIBRARY_LOADED, false , false, _name, _library, _names));

并在接收函数中作为数组访问它们。

private function onLibraryLoad(e:AppEvents):void 
        {
            _digestExternalLib.removeEventListener(AppEvents.LIBRARY_LOADED, onLibraryLoad);

            var currentIndex:int = AppData.navLocations.indexOf(e.arg[0], 0);

            AppData.libraries.push(e.arg[0]);
            AppData.libraryCon.push(e.arg[1]);
            AppData.libraryNames.push(e.arg[2]);

        }

我从一个正常运转的项目中抽出了这个......但是你应该能够收集到重要的东西...... 祝你好运!

答案 1 :(得分:0)

我真的没有看到代码有什么问题。只是为了测试,尝试在initWorld()方法结束时添加此语句:

_worldModel.dispatchEvent(new Event(CustomEvent.READY));

如果调用了update()方法,则表明您的现有dispatchEvent()方法未被调用。