2020-07-23 11:00:46 +08:00
|
|
|
module es {
|
2020-07-15 10:53:30 +08:00
|
|
|
/**
|
2020-07-23 11:00:46 +08:00
|
|
|
* 用于事件管理
|
2020-07-15 10:53:30 +08:00
|
|
|
*/
|
2020-07-23 11:00:46 +08:00
|
|
|
export class Emitter<T> {
|
2020-12-07 11:48:42 +08:00
|
|
|
private _messageTable: Map<T, Function[]>;
|
2020-06-15 12:16:23 +08:00
|
|
|
|
2020-07-28 16:25:20 +08:00
|
|
|
constructor() {
|
2020-12-07 11:48:42 +08:00
|
|
|
this._messageTable = new Map<T, Function[]>();
|
2020-07-23 11:00:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 开始监听项
|
|
|
|
|
* @param eventType 监听类型
|
|
|
|
|
* @param handler 监听函数
|
|
|
|
|
* @param context 监听上下文
|
|
|
|
|
*/
|
2020-07-28 16:25:20 +08:00
|
|
|
public addObserver(eventType: T, handler: Function, context: any) {
|
2020-12-07 11:48:42 +08:00
|
|
|
handler.bind(context);
|
|
|
|
|
|
|
|
|
|
let list: Function[] = this._messageTable.get(eventType);
|
2020-07-28 16:25:20 +08:00
|
|
|
if (!list) {
|
2020-07-23 11:00:46 +08:00
|
|
|
list = [];
|
|
|
|
|
this._messageTable.set(eventType, list);
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-07 11:48:42 +08:00
|
|
|
if (new linq.List(list).contains(handler))
|
2020-07-23 11:00:46 +08:00
|
|
|
console.warn("您试图添加相同的观察者两次");
|
2020-12-07 11:48:42 +08:00
|
|
|
list.push(handler);
|
2020-06-15 20:08:21 +08:00
|
|
|
}
|
2020-07-12 23:41:10 +08:00
|
|
|
|
2020-07-23 11:00:46 +08:00
|
|
|
/**
|
|
|
|
|
* 移除监听项
|
|
|
|
|
* @param eventType 事件类型
|
|
|
|
|
* @param handler 事件函数
|
|
|
|
|
*/
|
2020-07-28 16:25:20 +08:00
|
|
|
public removeObserver(eventType: T, handler: Function) {
|
2020-07-23 11:00:46 +08:00
|
|
|
let messageData = this._messageTable.get(eventType);
|
2020-12-07 11:48:42 +08:00
|
|
|
new linq.List(messageData).remove(handler);
|
2020-07-23 11:00:46 +08:00
|
|
|
}
|
2020-07-12 23:41:10 +08:00
|
|
|
|
2020-07-23 11:00:46 +08:00
|
|
|
/**
|
|
|
|
|
* 触发该事件
|
|
|
|
|
* @param eventType 事件类型
|
|
|
|
|
* @param data 事件数据
|
|
|
|
|
*/
|
2020-07-28 16:25:20 +08:00
|
|
|
public emit(eventType: T, data?: any) {
|
2020-12-07 11:48:42 +08:00
|
|
|
let list: Function[] = this._messageTable.get(eventType);
|
2020-07-28 16:25:20 +08:00
|
|
|
if (list) {
|
|
|
|
|
for (let i = list.length - 1; i >= 0; i--)
|
2020-12-07 11:48:42 +08:00
|
|
|
list[i](data);
|
2020-07-23 11:00:46 +08:00
|
|
|
}
|
|
|
|
|
}
|
2020-07-12 23:41:10 +08:00
|
|
|
}
|
2020-07-23 11:00:46 +08:00
|
|
|
}
|