您的位置:首页 > 其它

flex中dispatchEvent的用法(自定义事件) .

2014-07-16 15:11 411 查看
Evevt和EventDispatcher类在as3的事件机制中是很重要的角色,dispatchEvent()是EventDispatcher类的一个事件发送方法,它可以发送出Event类或其子类的实例,在as3中所有的显示对象都可以发送事件,因为as3中所有的显示对象都是EventDispatcher子类DisplayObject的实例。

发送事件有三种方式:继承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。

这个例子很简单,只是为了展示事件的发送接收,你还可以扩展自定义的Event类,带上你想发送的参数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: