export class Dispatcher {
private constructor() { }
public static instance = new Dispatcher()
private events: object = {}
public addEventListener(type: string, listener: Function) {
const listeners = this.events[type] || []
listeners.push(listener)
this.events[type] = listeners
}
public removeEventListener(type: string, listener: Function) {
const listeners = this.events[type] || []
const index = listeners.indexOf(listener)
listeners.splice(index, 1)
}
public dispatch(type: string, message: any) {
const listeners = this.events[type] || []
for (const listener of listeners) {
listener(message)
}
}
}
精简版(js):
const Eve = {
events: {},
on(type, listener) {
const listeners = this.events[type] || []
listeners.push(listener)
this.events[type] = listeners
},
off(type, listener) {
const listeners = this.events[type] || []
const index = listeners.indexOf(listener)
listeners.splice(index, 1)
},
emit(type, message) {
const listeners = this.events[type] || []
// 这里看情况,事件列表太长就不要slice
for (const listener of listeners.slice()) {
listener(message)
}
}
}
OnceDispatcher:
export class OnceDispatcher {
private constructor() {}
public static instance = new OnceDispatcher();
private events: object = {};
private routerParams = {} as any;
setRouterParams(k: string, v: any) {
this.routerParams[k] = v;
}
getRouterParams(k: string) {
return this.routerParams[k];
}
public addEventListener(type: string, listener: Function) {
this.events[type] = listener;
}
public removeEventListener(type: string) {
delete this.events[type];
}
public dispatch(type: string, message: any) {
const listener = this.events[type];
if (typeof listener === 'function') {
listener(message);
}
}
}