方法 (静态方法) | 功能 |
Dispatcher.on | 监听事件 参数0: 事件名称, 参数1: 监听方法的作用域 一般传this, 参数2: 监听方法 |
Dispatcher.off | 移除事件监听 参数0:事件名称,参数1:作用域,参数2: 监听的方法 ( 可选 ) 如果不填 会移除 作用域对象的所有监听方法 |
Dispathcer.dispatch | 派发事件 参数0: 事件名称, 参数1 多选可变参数 传入多个参数 |
Dispatcher.removeAllListener | 移除所有事件监听 无参数 |
案例1:
A类里进行 事件监听 和 结束移除事件
class A {
start(){
Dispatcher.on("game-start",this,this.onGameStart);
Dispatcher.on("game-end",this,this.onGameEnd);
}
onGameStart()
{
//游戏开始业务逻辑
}
onGameEnd( over?:boolean ){
//游戏在不同情况下退出的事件处理
//结束移除事件
//Dispatcher.off("game-start",this,this.onGameStart);
//Dispatcher.off("game-end",this,this.onGameEnd);
//如果需要移除这个类的所有事件 仅需传入this
Dispatcher.off("game-end",this);
}
}
B类里进行派发
class B {
// UI按钮点击处理
onClickButton(){
console.log("用户点击了屏幕");
Dispatcher.dispatch("game-start");
}
//游戏结束方法
onGameEnd(){
Dispatcher.dispatch("game-end",true);
console.log("用户正常退出房间结束游戏");
}
//退出按钮
onClickQuitGame()
{
Dispatcher.dispatch("game-end",false);
console.log("用户强行退出游戏");
}
}
案例2 闭包的监听和移除
class C {
start(){
//用一个临时的变量存储 闭包签名( 指针 )
let func = ()=>{
//游戏开始业务逻辑
//移除开始事件监听
Dispatcher.off("game-start",this,func );
};
//添加开始事件监听
Dispatcher.on("game-start",this,func);
//添加结束事件监听
Dispatcher.on("game-end",this,()=>{
//移除当前类的所有事件
Dispatcher.off("game-start",this);
});
}
}
上源码
export default class Dispatcher{
/**
* 事件池
*/
private static _handls: {
[key: string]: {
caller: any,
handl: Function
}[]
} = {};
/**
* 监听事件
* @param event 事件名称
* @param caller 作用域
* @param handl 回调方法
*/
public static on(event: string, caller: any, handl: Function): void {
if (undefined == Dispatcher._handls[event]) {
Dispatcher._handls[event] = [];
}
Dispatcher._handls[event].push({ caller, handl });
}
/**
* 移除监听
* @param event 事件名称
* @param caller 作用域
* @param handl 回调方法
*/
public static off(event: string, caller: any, handl: Function = undefined): void {
//获取事件队列
const list = Dispatcher._handls[event];
if (list && list instanceof Array) {
//遍历所有事件
for (let i = 0, count = list.length; i < count; i++) {
let e = list[i];
//移除对应事件
if (e.caller == caller && (undefined == handl || handl == e.handl)) {
list[i] = list[count - 1];
list.pop();
}
}
}
}
/**
* 移除所有事件
*/
public static removeAllListener() {
Dispatcher._handls = {};
}
/**
* 派发事件
* @param event 事件
* @param params 参数
*/
public static dispatch(event: string, ...params: any[]) {
const list = Dispatcher._handls[event];
if (list && list instanceof Array) {
for (let t of list) {
t.handl.call(t.caller, ...params);
}
}
}
}