How do I modify existing AS3 events so that I can pass data?

 ̄綄美尐妖づ 提交于 2019-12-04 04:33:51

You extended the Event class for it to dispatch with extra data, now if you want the Loader class to dispatch your custom event type, extend the Loader class to do that (or any other class you want to do this with). In this example I'll override URLLoader with this functionality (because Loader actually dispatches events from it's contentLoaderInfo, which needs two overridden classes, and I just want to keep it simple)


package com.net
{
    import flash.net.URLLoader;
    import flash.events.Event;

    import com.events.CustomEvent;

    public class CustomLoader extends URLLoader
    {
        // URLLoader already has a data property, so I used extraData
        public var extraData:*;

        override public function dispatchEvent(event: Event) : Boolean
        {
            var customEvent: CustomEvent = new CustomEvent(event.type, extraData, event.bubbles, event.cancelable);
            return super.dispatchEvent(customEvent);
        }
    }
}

Now to use this with your CustomEvent class try this code in your .fla


import com.net.CustomLoader;
import com.events.CustomEvent;

var loader: CustomLoader = new CustomLoader();
loader.extraData = "Extra Data";
loader.load(new URLRequest("test.xml"));
loader.addEventListener(Event.COMPLETE, loadComplete);

function loadComplete(event: CustomEvent) : void
{
    trace(event.data); // Extra Data
}

BAM! Custom data on your innately dispatched events!

Brian Hodge

The following shows the cleanest way to create a custom event. Typically event types have public static references typed in all capitol letters. When an event is dispatched, it passes an Event, or CustomEvent, object to the event handler method. This is where you can retrieve your passed value.

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

    public class CustomEvent extends Event 
    {
        public static const VALUE_CHANGED:String = "VALUE_CHANGED";
        public var value:Number;

        public function CustomEvent(pValue:Number) 
        { 
            super(CustomEvent.VALUE_CHANGED);
            value = pValue;
        } 
        public override function clone():Event 
        { 
            return new CustomEvent(value);
        }
    }
}

When we dispatch events, we create a new instance of the event to be passed as such.

private var _someValue:int = 12;
dispatchEvent(new CustomEvent(_somevalue));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!