Skip to content

Flex – Dispatching your very own custom event

October 5, 2008

Many friends of mine are noticing the emerging new Programming Language that’s sweeping the RIA world. ActionScript 3. Like many other OO languages, you can easily customize your own Event. Here’s a quick and simple way of understanding it.

The Problem: You want to create a timer, and after each elapsed time, you would like to dispatch an event and a variable that keeps updating (without using global variables, and ensuring decoupling).

CountdownTimer.as : A timer which elapses ever second and displays a countdown of a time remaining with fixed endTime. 

CountDownTimer.as:
// in the constructor
ticker = new Timer(1000);
ticker.addEventListener(TimerEvent.TIMER, onTick);
ticker.start();

private function onTick(evt:TimerEvent):void {
   var myEvent:MyTimerEvent = new MyTimerEvent(“secElapse”);
       myEvent.timeLeft = getCountDown(countDownTime – (new Date()).getTime());
   dispatchEvent(myEvent);
}

——
 

MyTimerEvent.as: Our very own customized timer
public class MyTimerEvent extends Event {
   private var theTime:String;

   public function MyTimerEvent( type:String ) {
      super(type);
   }

   public function set timeLeft ( time:String ):void {
      theTime = time;
   }

   public function get timeLeft ():String {
      return theTime;
   }
}

——-

Our MXML where all the action converges on CreationComplete=”onCC()” :
      private function onCC():void {
     // listner to secElapse dispatcher
     countDown = new CountdownTimer();
     countDown.addEventListener("secElapse", updateTime);
   }

   // Update the display timer
   private function updateTime (e:MyTimerEvent):void {
      countDown.endTime = m_endTime;
      m_updatedTimeRemaining = e.timeLeft;
   }

Advertisements

From → Uncategorized

One Comment
  1. underke permalink

    very helpfull! thanxs
    now only a Duplicate function definition in my getter and setter I need to fix.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: