发送事件有三种方式:继承EventDispatcher,如sprite等显示对象、复合EventDispatcher或其子类、实现IEventDispatcher接口。
个人认为复合EventDispatcher在实际应用中用的比较多,没有找到合适例子,自己写了一个很简单的,仅供参考,为了演示把简单的问题复杂话了,首先画一个矩形,点击矩形后发送一个事件,矩形接收事件后alpha变为0;
自定义事件:
package{
import flash.events.Event;
public class MyEvent extends Event{
public static const ALPHA:String = "alpha";
public function MyEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false){
super(type, bubbles, cancelable);
}
}
}
package{
import flash.display.Sprite;
public class Sample extends Sprite{
public function Sample(){
this.graphics.beginFill(0xff6600);
this.graphics.drawRect(50,50,100,50);
this.graphics.endFill();
this.addEventListener(MyEvent.ALPHA,blackHandler);
}
private function blackHandler(evt:MyEvent){
this.alpha = 0;
}
}
}
主类:
package{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Main extends Sprite{
private var sample:Sample;
public function Main(){
sample = new Sample();
//注册事件侦听器
sample.addEventListener(MouseEvent.CLICK,clickHandler);
addChild(sample);
}
private function clickHandler(evt:MouseEvent){
//发送事件
sample.dispatchEvent(new MyEvent(MyEvent.ALPHA));
}
}
}
注:在as3中只有事件的发送者才能侦听事件。在Main类中sample实例发送的事件也只有sample注册的侦听器才能侦听,在Sample中的this正是指向了sample。