在第一个场景声明eventTarget
const {ccclass, property} = cc._decorator;
@ccclass
export default class SplashScene extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
static eventTarget: any;
start () {
// init logic
this.label.string = '加载场景';
setTimeout(()=>{
SplashScene.eventTarget = new cc.EventTarget();
cc.director.loadScene('StartScene',()=>{
console.log('>>StartScene Launch Callback!');
});
}, 1);
}
}
首先声明eventTarget为static,在加载下一场景或者下一个脚本时实例化为一个 EventTarget 对象。现在我们可以在任意地方使用eventTarget来实现对事件的监听和发射,使用具体方法为:
声明eventTarget的类的名字.on()
声明eventTarget的类的名字.emit()
声明eventTarget的类的名字.off()
监听事件
SplashScene.eventTarget.on(GameEvent.INIT_POKER,this.m_GameView.OnEventInit,this.m_GameView)
SplashScene.eventTarget.on(GameEvent.PLAY,this.m_GameView.OnEventPlay,this.m_GameView)
GameEvent
该类定义了各种事件
export default class GameEvent
{
public static INIT_POKER: string = "INIT_POKER";
public static PLAY: string = "PLAY";
}
取消监听事件
当我们不再关心某个事件时,我们可以使用 off 接口关闭对应的监听事件。
SplashScene.eventTarget.off(GameEvent.INIT_POKER,this.m_GameView.OnEventInit)
发射事件
发射事件可以通过 eventTarget.emit() 接口来实现,方法如下:
SplashScene.eventTarget.emit(GameEvent.INIT_POKER,this._pokers)
SplashScene.eventTarget.emit(GameEvent.PLAY)
总结
需要在多脚本使用监听和发射事件EventTarget 类需要全局使用一个实例化的EventTarget 类的对象,不要每次都重新声明。