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

41 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-06-15 12:16:23 +08:00
class Emitter<T> {
2020-07-12 23:41:10 +08:00
private _messageTable: Map<T, FuncPack[]>;
2020-06-15 12:16:23 +08:00
constructor(){
2020-07-12 23:41:10 +08:00
this._messageTable = new Map<T, FuncPack[]>();
2020-06-15 12:16:23 +08:00
}
2020-07-12 23:41:10 +08:00
public addObserver(eventType: T, handler: Function, context: any){
let list: FuncPack[] = this._messageTable.get(eventType);
2020-06-15 12:16:23 +08:00
if (!list){
list = [];
this._messageTable.set(eventType, list);
}
if (list.contains(handler))
console.warn("您试图添加相同的观察者两次");
2020-07-12 23:41:10 +08:00
list.push(new FuncPack(handler, context));
2020-06-15 12:16:23 +08:00
}
public removeObserver(eventType: T, handler: Function){
this._messageTable.get(eventType).remove(handler);
}
2020-07-12 23:30:48 +08:00
public emit(eventType: T, data?: any){
2020-07-12 23:41:10 +08:00
let list: FuncPack[] = this._messageTable.get(eventType);
if (list){
for (let i = list.length - 1; i >= 0; i --)
2020-07-12 23:41:10 +08:00
list[i].func.call(list[i].context, data);
}
2020-06-15 12:16:23 +08:00
}
2020-07-12 23:41:10 +08:00
}
class FuncPack {
public func: Function;
public context: any;
constructor(func: Function, context: any){
this.func = func;
this.context = context;
}
2020-06-15 12:16:23 +08:00
}