新增事件发送接收器

This commit is contained in:
yhh
2020-06-15 12:16:23 +08:00
parent 16892eb7af
commit c3120d791f
15 changed files with 141 additions and 123 deletions

View File

@@ -0,0 +1,29 @@
class Emitter<T> {
private _messageTable: Map<T, Function[]>;
constructor(){
this._messageTable = new Map<T, Function[]>();
}
public addObserver(eventType: T, handler: Function){
let list: Function[] = this._messageTable.get(eventType);
if (!list){
list = [];
this._messageTable.set(eventType, list);
}
if (list.contains(handler))
console.warn("您试图添加相同的观察者两次");
list.push(handler);
}
public removeObserver(eventType: T, handler: Function){
this._messageTable.get(eventType).remove(handler);
}
public emit(eventType: T, data: any){
let list: Function[] = this._messageTable.get(eventType);
for (let i = list.length - 1; i >= 0; i --)
list[i](data);
}
}