emitter 支持 context

This commit is contained in:
YHH
2020-07-12 23:41:10 +08:00
parent 14598f08c7
commit f0e04b6981
7 changed files with 51 additions and 17 deletions

View File

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