#12 fix Emitter类移除监听时是否有错

This commit is contained in:
yhh
2020-07-15 10:53:30 +08:00
parent 983c8fbc99
commit 7dffb4d94a
10 changed files with 48 additions and 8 deletions

View File

@@ -1,3 +1,6 @@
/**
* 用于事件管理
*/
class Emitter<T> {
private _messageTable: Map<T, FuncPack[]>;
@@ -5,6 +8,12 @@ class Emitter<T> {
this._messageTable = new Map<T, FuncPack[]>();
}
/**
* 开始监听项
* @param eventType 监听类型
* @param handler 监听函数
* @param context 监听上下文
*/
public addObserver(eventType: T, handler: Function, context: any){
let list: FuncPack[] = this._messageTable.get(eventType);
if (!list){
@@ -17,10 +26,22 @@ class Emitter<T> {
list.push(new FuncPack(handler, context));
}
/**
* 移除监听项
* @param eventType 事件类型
* @param handler 事件函数
*/
public removeObserver(eventType: T, handler: Function){
this._messageTable.get(eventType).remove(handler);
let messageData = this._messageTable.get(eventType);
let index = messageData.findIndex(data => data.func == handler);
messageData.removeAt(index);
}
/**
* 触发该事件
* @param eventType 事件类型
* @param data 事件数据
*/
public emit(eventType: T, data?: any){
let list: FuncPack[] = this._messageTable.get(eventType);
if (list){
@@ -30,8 +51,13 @@ class Emitter<T> {
}
}
/**
* 用于包装事件的一个小类
*/
class FuncPack {
/** 函数 */
public func: Function;
/** 上下文 */
public context: any;
constructor(func: Function, context: any){