修复emitter
This commit is contained in:
@@ -1,12 +1,27 @@
|
||||
module es {
|
||||
/**
|
||||
* 用于包装事件的一个小类
|
||||
*/
|
||||
export class FuncPack {
|
||||
/** 函数 */
|
||||
public func: Function;
|
||||
/** 上下文 */
|
||||
public context: any;
|
||||
|
||||
constructor(func: Function, context: any) {
|
||||
this.func = func;
|
||||
this.context = context;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于事件管理
|
||||
*/
|
||||
export 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[]>();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -16,17 +31,15 @@ module es {
|
||||
* @param context 监听上下文
|
||||
*/
|
||||
public addObserver(eventType: T, handler: Function, context: any) {
|
||||
handler.bind(context);
|
||||
|
||||
let list: Function[] = this._messageTable.get(eventType);
|
||||
let list: FuncPack[] = this._messageTable.get(eventType);
|
||||
if (!list) {
|
||||
list = [];
|
||||
this._messageTable.set(eventType, list);
|
||||
}
|
||||
|
||||
if (new linq.List(list).contains(handler))
|
||||
if (list.findIndex(funcPack => funcPack.func == handler) != -1)
|
||||
console.warn("您试图添加相同的观察者两次");
|
||||
list.push(handler);
|
||||
list.push(new FuncPack(handler, context));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,7 +49,9 @@ module es {
|
||||
*/
|
||||
public removeObserver(eventType: T, handler: Function) {
|
||||
let messageData = this._messageTable.get(eventType);
|
||||
new linq.List(messageData).remove(handler);
|
||||
let index = messageData.findIndex(data => data.func == handler);
|
||||
if (index != -1)
|
||||
new linq.List(messageData).removeAt(index);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -45,10 +60,10 @@ module es {
|
||||
* @param data 事件数据
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user