雪原xy 发表于 2019-1-18 15:16:10

事件练习之六(用接口来实现事件发送类)

//用接口来实现发送事件;
//文档类;
package {
import flash.display.Sprite;
import flash.events.Event;
import son.InterDis;
public class doc extends Sprite{
//定义一个InterDis的实例,但没初始化;
var sender:InterDis;
//构造函数里只有一个init()方法;
public function doc():void{
init();
}
//用下面的方法来初始化实例,并执行相应的动作;
private function init():void{
//初始化实例;
sender=new InterDis("赵老师");
//注册侦听器;
sender.addEventListener("上课",eFun);
//发送事件;
sender.dispatchEvent(new Event("上课"));
//移除侦听器;
sender.removeEventListener("上课",eFun);
//检查侦听器有没有移除成功;
trace(sender.hasEventListener("上课"));
}
//定义侦听器函数;
private function eFun(e:Event):void{
//调用事件类的type属性,并根据类型作出不同的动作;
if(e.type=="上课"){
trace(e.type);
//调用target属性访问实例的nam属性;
trace(e.target.nam+"好!");
}
else {
trace("老师再见!");
}
}
}
}

//用接口的方式来创建发送事件类;
packageson{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
//定义一个InterDis类,实现IEventDispatcher接口;
public class InterDis implements IEventDispatcher{
//首先定义一个公开的属性_sender,类型为:EventDispatcher,相当于复合EventDispatcher!
public var_sender:EventDispatcher;
//定义一个nam属性;
public var nam:String;
//在构造函数中为nam属性赋值;
public function InterDis(str:String):void{
//注意参数是"this";
_sender=new EventDispatcher(this);
nam=str;
}
//接下来是实现IEventDispatcher的几个公开的方法;
//第一个是addEventListener方法;
//五个参数中最常用的是前两个,后三个保持默认;
public function addEventListener(type:String,fun:Function,useC:Boolean=false,pro:int=0,useW:Boolean=true):void{
//这里可以加入其他的代码;
trace("我在侦听时加入了代码!")
//用属性_sender的addEventListener方法来实现(其他的方法类似);
_sender.addEventListener(type,fun,useC,pro,useW);
}
//第二个是dispatchEvent方法;
//注意:它有返回值,类型是:Boolean;
public function dispatchEvent(evt:Event):Boolean{
return _sender.dispatchEvent(evt);
}
//第三个是removeEventListener方法;
public function removeEventListener(type:String,fun:Function,useC:Boolean=false):void{
_sender.removeEventListener(type,fun,useC);
}
//剩下的两个方法不太常用,但也要实现;
public function hasEventListener(type:String):Boolean{
return _sender.hasEventListener(type);
}
public function willTrigger(type:String):Boolean{
return _sender.willTrigger(type);
}
}
}


雪原xy 发表于 2019-1-18 15:17:19

1、实现接口必须要重写接口的公开方法,
   但是我们根本不知道如何去写addEventListener等这些方法,
   于是教材想出了一个好办法,
      就是复合EventDispatcher类作为属性,
      直接调用属性的这些方法!真是聪明!
2、接口还有一个优点就是可以在方法里添加代码;
学习中的困惑:
1、真的很想知道addEventListener和dispatchEvent这两个方法是怎么写的,内容是什么?
2、下面这句代码中的this到底是什么?为什么只能在构造函数中使用this?
   _sender:EventDispatcher=new EventDispatcher(this);
3、dispatchEvent方法为什么有一个Boolean类型的返回值?
页: [1]
查看完整版本: 事件练习之六(用接口来实现事件发送类)

感谢所有支持论坛的朋友:下面展示最新的5位赞助和充值的朋友……更多赞助和充值朋友的信息,请查看:永远的感谢名单

SGlW(66139)、 anghuo(841)、 whdsyes(255)、 longxia(60904)、 囫囵吞澡(58054)

下面展示总排行榜的前3名(T1-T3)和今年排行榜的前3名的朋友(C1-C3)……更多信息,请查看:总排行榜今年排行榜

T1. fhqu1462(969)、 T2. lwlpluto(14232)、 T3. 1367926921(962)  |  C1. anghuo(147)、 C2. fdisker(27945)、 C3. 囫囵吞澡(58054)