Passing Data with Custom Events in AS3


/ Published in: ActionScript 3
Save to your folder(s)

This is an event class that lets you package related events together and send custom data with the event, very useful for MVC applications.


Copy this code and paste it in your HTML
  1. package utils {
  2. import flash.events.Event;
  3.  
  4. public class CustomEvent extends Event
  5. {
  6. /* Place as many events as you want to include in this class */
  7. public static const EXAMPLE_EVENT:String = "exampleEvent";
  8. public static const ANOTHER_EVENT:String = "anotherEvent";
  9.  
  10. /* Create properties to hold data that you want to pass with your event
  11. Include as many as you like. */
  12. public var dataObj:Object;
  13.  
  14. public function CustomEvent(type:String, dataObj:Object = null)
  15. {
  16. this.dataObj = dataObj;
  17. /* Call the super function which fires off the event
  18. set the event type, bubbling and cancelable properties */
  19. super(type, false, false);
  20. }
  21.  
  22. /* Duplicates the instance of the event */
  23. override public function clone():Event
  24. {
  25. /* This is the event that will be received by your handler function */
  26. return new CustomEvent(type, dataObj);
  27. }
  28. }
  29. }
  30.  
  31. /********** To use this class would look something like this **************/
  32.  
  33. /* Dispatch event with data to be passed
  34. dataObj.name = "test data";
  35. dispatchEvent(new CustomEvent(CustomEvent.EXAMPLE_EVENT, dataObj));
  36.  
  37. /* Listen for your custom event
  38. addEventListener(CustomEvent.EXAMPLE_EVENT, handleExample);
  39.  
  40. /* Handle your custom event with custom data
  41. function handleExample(event:CustomEvent):void {
  42. var mydata:Object = event.dataObj;
  43. }
  44.  
  45. /*************************************************************************/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.