flexr

Flex – Dispatching your very own custom event

with one comment

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;
   }

Written by Jester theFool

October 5, 2008 at 10:40 pm

One Response

Subscribe to comments with RSS.

  1. First blog I read after wakeup from sleep today!

    —————————-
    Are you tension? panic?

    Terry

    March 3, 2009 at 2:55 pm


Leave a Reply