Main类
class Main extends eui.Component {
public constructor()
{
super();
}
public childrenCreated()
{
super.childrenCreated();
this.callEvent();
}
//调用ScreenEvent类的函数
private callEvent()
{
//调用ScreenEvent下的screen_1函数,不添加事件侦听
ScreenEvent.getInstance().screen_1();
//调用ScreenEvent下的screen_2函数(通过注册"SCREEN_COMPLETE"监听),添加事件侦听
let a:ScreenEvent = new ScreenEvent();
a.addEventListener("SCREEN_COMPLETE",this.screenComplete,this);
a.screen_2();
//a.addEventListener 和 a.screen_2(); 一定不要写反,否则监听不到
}
private screenComplete(evt:ScreenEvent){
//通过evt['data']来提取监听事件传来的值
console.log(evt['data']);
}
}
ScreenEvent类
class ScreenEvent extends egret.EventDispatcher{
//单例,通过此可不声明类,直接调用(调用1)ScreenEvent.getInstance().screen_1();
private static instance:ScreenEvent;
public static getInstance():ScreenEvent{
if(this.instance == null){
this.instance = new ScreenEvent();
}
return this.instance;
}
public screen_1(){
console.log('调用方式-1');
}
//第2种调用方式,通过写的"SCREEN_COMPLETE"在main中监听次函数的执行
public screen_2(){
let dataArr:any = {};
for(let i=0;i<10;i++){
dataArr[i] = i+7;
}
this.dispatchEvent(new egret.Event("SCREEN_COMPLETE", false, false, dataArr));
}
}