#12 fix Emitter类移除监听时是否有错
This commit is contained in:
@@ -48,7 +48,7 @@ declare interface Array<T> {
|
||||
* 移除数组元素
|
||||
* @param element 数组元素
|
||||
*/
|
||||
remove(element): boolean;
|
||||
remove(element: T): boolean;
|
||||
/**
|
||||
* 移除特定索引数组元素
|
||||
* @param index 索引
|
||||
|
||||
@@ -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){
|
||||
|
||||
Reference in New Issue
Block a user