PDA

View Full Version : EventDispatcher


dv8
09-09-2003, 03:56 PM
Peter Joel Hall of http://www.peterjoel.com talks about in his blog the replacement for AsBroadcaster, the supported EventDispatcher (http://www.peterjoel.com/blog/index.php?archive=2003_08_31_archive.xml&showComments=106262996541623604#106262996541623604 ).

So I did some digging...

EventDispatcher works the same way as AsBroadcaster, but more powerful. Enabling the developer to return the Event type and Event target.

Example of EventDispatcher Class -

/*
Timer Class
- This is one of my favorites. It's not mine by origin, but I redid it for AS2.0
*/
// Import event class
import mx.events.EventDispatcher;
class com.flashmove.Timer {
// declare properties and methods
var _timeout:Number;
var intervalid:Number;
var dispatchEvent:Function;
var addEventListener:Function;
var removeEventListener:Function;
//Timer Constructor
function Timer() {
// tell EventDispatcher to allow inheritance to Timer
EventDispatcher.initialize(this);
}
//public methods
public function toString() {
return "[object Timer]";
}
public function start(timeout:Number) {
//when does this timer, fire?
_timeout = timeout;
//start the timer
reset();
}
public function stop() {
//get rid of the interval
clearInterval(intervalid);
}
public function reset() {
stop();
//set a new interval
intervalid = setInterval(this, "fire", _timeout);
}
//private method
private function fire() {
//tell all the listeners that this timer has runout
dispatchEvent({type:"onTimeOut"});
}
}


//Usage -
import com.flashmove.Timer;

var timer_obj:Timer = new Timer();
var listener:Object = {};
listener.onTimeOut = function () {
trace(e.type + " was broadcast by " + e.target); //output: onTimeOut was broadcast by [object Timer]
}
timer_obj.addEventListener("onTimeOut", listener);
timer_obj.start(1000);


I'm still learning more, but I thought I'd share with my progress.