4 Replies Latest reply on Apr 13, 2007 11:08 AM by ntsiii

    Dispatching data events

    Dzihan Level 1
      Hello.

      Has anyone ever found a way how to pass data to a function called by an eventListener?
      something like:

      var str:String = "myData"
      dispatcher.addEventListener("dataAvailable", myFunction);
      dispatcher.dispatchEvent(new Event("dataAvailable"), str)

      public function myFunction(e:Event, data:String):void
      {
      trace(data);
      }

      This would be very useful sometimes.
        • 1. Re: Dispatching data events
          peterent Level 2
          You need to create your own event class (see Custom Events in the Flex docs). Something like this:

          package {
          import flash.events.Event;
          public class MyEvent extends Event
          {
          public function MyEvent( type:String, extradata:String )
          {
          super(type);
          data = extradata;
          }
          public var data:String;
          }
          }

          You would use this like:
          addEventListener( "dataAvailable", myFunction);
          dispatchEvent( new MyEvent("dataAvailable", str) );
          ...
          private function myFunction( e:MyEvent ) : void
          {
          ...
          }
          • 2. Re: Dispatching data events
            ntsiii Level 3
            But remember, the normal event object gives you access to the "target", the thing that raised the event, so if your data is available on that target object that dispatched the event, you can access it in a handler, event.target.mydata.

            Tracy
            • 3. Re: Dispatching data events
              Dzihan Level 1
              Thx Tracy for the hint. i know i can access the target but the target holds several data so i prefer to send the one i need directly with the event.
              i gonna try peterents solution.
              thx for your replies!
              • 4. Re: Dispatching data events
                ntsiii Level 3
                But using "target" is not "sending" any data. It is just a reference. A custom event will be more complicated and less efficient. Don't do that if you don't need it.
                Tracy