Files
esengine/source/src/Utils/Emitter.ts

70 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-07-23 11:00:46 +08:00
module es {
/**
2020-07-23 11:00:46 +08:00
*
*/
2020-07-23 11:00:46 +08:00
export class FuncPack {
/** 函数 */
public func: Function;
/** 上下文 */
public context: any;
2020-06-15 12:16:23 +08:00
2020-07-23 11:00:46 +08:00
constructor(func: Function, context: any){
this.func = func;
this.context = context;
}
2020-06-15 12:16:23 +08:00
}
/**
2020-07-23 11:00:46 +08:00
*
*/
2020-07-23 11:00:46 +08:00
export class Emitter<T> {
private _messageTable: Map<T, FuncPack[]>;
2020-06-15 12:16:23 +08:00
2020-07-23 11:00:46 +08:00
constructor(){
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){
list = [];
this._messageTable.set(eventType, list);
}
2020-07-27 17:27:32 +08:00
if (list.findIndex(funcPack => funcPack.func == handler) != -1)
2020-07-23 11:00:46 +08:00
console.warn("您试图添加相同的观察者两次");
list.push(new FuncPack(handler, context));
}
2020-07-12 23:41:10 +08:00
2020-07-23 11:00:46 +08:00
/**
*
* @param eventType
* @param handler
*/
public removeObserver(eventType: T, handler: Function){
let messageData = this._messageTable.get(eventType);
let index = messageData.findIndex(data => data.func == handler);
if (index != -1)
messageData.removeAt(index);
}
2020-07-12 23:41:10 +08:00
2020-07-23 11:00:46 +08:00
/**
*
* @param eventType
* @param data
*/
public emit(eventType: T, data?: any){
let list: FuncPack[] = this._messageTable.get(eventType);
if (list){
for (let i = list.length - 1; i >= 0; i --)
list[i].func.call(list[i].context, data);
}
}
2020-07-12 23:41:10 +08:00
}
2020-07-23 11:00:46 +08:00
}