2008
05.26

AS3 simple custom event example

This is a consise exmple of how to create a custom event in ActionScript 3. Firstly, create a custom event that extends Event, here this is called “SimpleItemEvent”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package{
 /* really simple event examlple */
 import flash.events.Event;
 import SimpleItem;

 public class SimpleItemEvent extends Event {
    public static const COMPLETE:String = "complete";
    public static const READY:String = "ready";
    private var _si:SimpleItem;
    public function SimpleItemEvent(type:String, si:SimpleItem)  {
       super(type,true);
       _si = si;
    }
    public override function  clone():Event  {
       return new SimpleItemEvent(type,_si);
    }
    public function get simpleItem():SimpleItem  {
       return _si;
    }
 }
}

Now create a somthing that uses the custom event class above, in this example the class SimpleItem uses a timer to trigger a custom event.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package
{
  import flash.display.Sprite;
  import flash.utils.Timer;
  import flash.events.Event;
  import flash.events.TimerEvent;
  import SimpleItemEvent;

  public class SimpleItem extends Sprite{
        private var timer:Timer;
        public function SimpleItem(){
        }
    public function start()  {
         timer = new Timer(4000,1);
         timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerComplete);
         timer.start();
         dispatchEvent(new SimpleItemEvent(SimpleItemEvent.READY, this));
    }
    private function timerComplete(e:TimerEvent){
         dispatchEvent(new SimpleItemEvent(SimpleItemEvent.COMPLETE, this));
    }
  }
}

Finally create we use a SimpleItem in our code (this could be in our code behind of our FLA), and add listeners to it’s events.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package {
   import flash.display.Sprite;
   import SimpleItem;
   import SimpleItemEvent;

   public class Simple extends Sprite {
     public function Simple()     {
       var si = new SimpleItem();
       si.addEventListener(SimpleItemEvent.READY,traceReady);
       si.addEventListener(SimpleItemEvent.COMPLETE, traceComplete);
       si.start();
     }
     private function traceReady(e:SimpleItemEvent):void  {
       trace(e.target + "ready");
     }
     private function traceComplete(e:SimpleItemEvent):void     {
       trace("complete");
     }
  }
}

download the example.

Bookmark and Share

No Comment.

Add Your Comment