#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

@@ -0,0 +1,3 @@
{
"typescript.tsdk": "./node_modules/typescript/lib"
}

View File

@@ -8,7 +8,7 @@ declare interface Array<T> {
findAll(predicate: Function): Array<T>;
contains(value: any): boolean;
removeAll(predicate: Function): void;
remove(element: any): boolean;
remove(element: T): boolean;
removeAt(index: any): void;
removeRange(index: any, count: any): void;
select(selector: Function): Array<T>;

View File

@@ -4883,7 +4883,9 @@ var Emitter = (function () {
list.push(new FuncPack(handler, context));
};
Emitter.prototype.removeObserver = function (eventType, handler) {
this._messageTable.get(eventType).remove(handler);
var messageData = this._messageTable.get(eventType);
var index = messageData.findIndex(function (data) { return data.func == handler; });
messageData.removeAt(index);
};
Emitter.prototype.emit = function (eventType, data) {
var list = this._messageTable.get(eventType);

File diff suppressed because one or more lines are too long

View File

@@ -48,7 +48,7 @@ declare interface Array<T> {
* 移除数组元素
* @param element 数组元素
*/
remove(element): boolean;
remove(element: T): boolean;
/**
* 移除特定索引数组元素
* @param index 索引

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){