Study for EventDispatcher


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

A CountEvent class’s instance counts up from 0 to 50, then dispatches "countComplete" event. Here’s a result below.

1
2
3
.
.
.
48
49
50
Count Complete


Copy this code and paste it in your HTML
  1. // EventTest.as
  2.  
  3. class EventTest extends MovieClip {
  4. var countEvent:MovieClip;
  5.  
  6. public function EventTest() {
  7. countEvent = this.attachMovie(
  8. "countEvent",
  9. "countEvent",
  10. this.getNextHighestDepth()
  11. );
  12. countEvent.addEventListener("countComplete", this.countComplete);
  13. countEvent.startCount();
  14. }
  15.  
  16. public function countComplete(event:Object):Void {
  17. trace("Count Complete");
  18. }
  19. }
  20.  
  21. //----------------- separated files -----------------
  22.  
  23. // CountEvent.as
  24.  
  25. import mx.events.EventDispatcher;
  26.  
  27. dynamic class CountEvent extends MovieClip {
  28. var counter:Number;
  29. var max:Number;
  30.  
  31. public function CountEvent() {
  32. EventDispatcher.initialize(this);
  33. counter = 0;
  34. max = 50;
  35. }
  36.  
  37. public function startCount():Void {
  38. this.onEnterFrame = function():Void {
  39. counter++;
  40. trace(counter);
  41. if(counter >= max) {
  42. delete this.onEnterFrame;
  43. this.dispatchEvent({type: "countComplete"});
  44. }
  45. }
  46. }
  47. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.