You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
2.3 KiB
91 lines
2.3 KiB
4 years ago
|
/**
|
||
|
* 事件系统
|
||
|
*/
|
||
|
export class AxMessageSystem {
|
||
|
/** 监听数组 */
|
||
|
private static listeners = {};
|
||
|
|
||
|
/**
|
||
|
* 注册事件
|
||
|
* @param name 事件名称
|
||
|
* @param callback 回调函数
|
||
|
* @param context 上下文
|
||
|
*/
|
||
|
public static addListener(name: string, callback: () => void, context: any) {
|
||
|
const observers: Observer[] = AxMessageSystem.listeners[name];
|
||
|
if (!observers) {
|
||
|
AxMessageSystem.listeners[name] = [];
|
||
|
}
|
||
|
AxMessageSystem.listeners[name].push(new Observer(callback, context));
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 移除事件
|
||
|
* @param name 事件名称
|
||
|
* @param callback 回调函数
|
||
|
* @param context 上下文
|
||
|
*/
|
||
|
public static removeListener(name: string, callback: () => void, context: any) {
|
||
|
const observers: Observer[] = AxMessageSystem.listeners[name];
|
||
|
if (!observers) { return; }
|
||
|
const length = observers.length;
|
||
|
for (let i = 0; i < length; i++) {
|
||
|
const observer = observers[i];
|
||
|
if (observer.compar(context)) {
|
||
|
observers.splice(i, 1);
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
if (observers.length === 0) {
|
||
|
delete AxMessageSystem.listeners[name];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 发送事件
|
||
|
* @param name 事件名称
|
||
|
*/
|
||
|
public static send(name: string, ...args: any[]) {
|
||
|
const observers: Observer[] = AxMessageSystem.listeners[name];
|
||
|
if (!observers) { return; }
|
||
|
const length = observers.length;
|
||
|
for (let i = 0; i < length; i++) {
|
||
|
const observer = observers[i];
|
||
|
observer.notify(name, ...args);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 观察者
|
||
|
*/
|
||
|
class Observer {
|
||
|
/** 回调函数 */
|
||
|
private callback: () => void;
|
||
|
/** 上下文 */
|
||
|
private context: any = null;
|
||
|
|
||
|
constructor(callback: () => void, context: any) {
|
||
|
const self = this;
|
||
|
self.callback = callback;
|
||
|
self.context = context;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 发送通知
|
||
|
* @param args 不定参数
|
||
|
*/
|
||
|
notify(...args: any[]): void {
|
||
|
const self = this;
|
||
|
self.callback.call(self.context, ...args);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 上下文比较
|
||
|
* @param context 上下文
|
||
|
*/
|
||
|
compar(context: any): boolean {
|
||
|
return context === this.context;
|
||
|
}
|
||
|
}
|