R – Attaching a property to an event in Flex/AS3

actionscript-3apache-flexcustom-eventsevent-dispatchingevents

I have a parameter that needs to be passed along with an event. After unsuccessful attempts to place it on the type by extending the class, I've been advised in another SO question to write a custom event.

I tried this before but I couldn't figure out how to send it, because I just want to send another parameter with a normal Event.COMPLETE event on a FileReference. I can't have Event.COMPLETE fire and then dispatch my event because then I'll be in the same boat … the needed parameter won't be in the initial Event.COMPLETE object so I won't be able to dispatch a new event passing that parameter on to the code that actually performs the work.

All help on this is greatly appreciated, need it badly. Thanks.

Basically, I need to replace the Event.COMPLETE functionality exactly as it is, I just need an event that will hold my extra property. Please tell me there's some way to do this.

Best Answer

first you need to add an event listener to the Event.COMPLETE as normal since it is going to be dispatched automatically and theres nothing you can do about it. Inside that event handler you can then dispatch your own custom even that the rest of the application listens for with your custom property attached to it. heres a quick example:

your event handling code would look like:

yourObject.addEventListener(Event.COMPLETE, function(event:Event):void{

  var myEvt:MyEvent = new MyEvent(MyEvent.COMPLETE, myCustomProperty);
  dispatchEvent( myEvt );

})

and the MyEvent class looks like:

package
{

  import flash.events.Event;

  public class MyEvent extends Event
  {

    public static const COMPLETE:String = "MyEventComplete";

    var myCustomProperty:*;

    public function MyCustomEvent(type:String, prop:*) :void
    {

      myCustomProperty = prop;

      super(type);
      // if you want your event to bubble 
      // be sure to specify : super(type, true)
    }

   //override clone() so your event bubbles correctly
   public override function clone() :MyEvent {

     return new MyEvent(this.type, this.myCustomProperty)

   }
  }
}

you can now add event listeners for your custom event just like any other event:

addEventListener(MyCustomEvent.COMPLETE, someFunction);