Custom event listener example


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



Copy this code and paste it in your HTML
  1. //MAIN.as
  2.  
  3.  
  4. package {
  5. import flash.display.MovieClip;
  6. import flash.events.MouseEvent;
  7. import flash.events.Event;
  8.  
  9. public class Main extends MovieClip{
  10.  
  11.  
  12. //public static const customEvent:String = "customEvent";
  13.  
  14. public function Main() {
  15. // constructor code
  16. var ball:Ball = new Ball(this);
  17. addChild(ball);ball.x = 100; ball.y = 100;
  18. ball.addEventListener("my event", listenForClick);
  19.  
  20.  
  21.  
  22. }
  23.  
  24.  
  25. // listening to the ball
  26. private function listenForClick (evt:Event) : void {
  27. trace("i hear it"+evt.target);
  28. evt.target.alpha = .4;
  29. }
  30.  
  31. // run from the ball
  32. public function init (passed:String) : void {
  33. trace("initalise "+passed);
  34. }
  35.  
  36. }
  37.  
  38.  
  39.  
  40.  
  41. //BALL.as
  42.  
  43. package {
  44. import flash.display.MovieClip;
  45. import flash.events.MouseEvent;
  46. import flash.events.Event;
  47.  
  48. public class Ball extends MovieClip{
  49.  
  50. private var ballVar:String = "ochie";
  51. private var targ:MovieClip;
  52.  
  53. public function Ball(tt:MovieClip) {
  54. // constructor code
  55. targ = tt;
  56. stop();
  57. buttonMode = true;
  58. addEventListener(MouseEvent.MOUSE_OVER, ball_over);
  59. addEventListener(MouseEvent.MOUSE_OUT, ball_out);
  60. addEventListener(MouseEvent.CLICK, ball_clicked);
  61. }
  62.  
  63. private function ball_over (e:MouseEvent) : void {
  64. gotoAndStop(2);
  65. }
  66.  
  67. private function ball_out (e:MouseEvent) : void {
  68. gotoAndStop(1);
  69. }
  70.  
  71. private function ball_clicked (e:MouseEvent) : void {
  72.  
  73. trace("clik");
  74. dispatchEvent(new Event("my event"));
  75. targ.init(ballVar);
  76.  
  77. }
  78.  
  79. }
  80.  
  81. }
  82.  
  83.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.