一个简单event bus的实现
发布订阅者模式
type emitKey = number | string | symbol;
type func = (...args: any) => void;
interface BusInterface {
emit: (key: emitKey, ...args: any) => void;
on: (key: emitKey, fn: func) => void;
}
class Bus implements BusInterface {
emit: (key: emitKey, ...args: any) => void = (key, ...args) => {
const handlers: Array<func> = this.list[key] || [];
handlers.forEach((fn: func) => fn(...args));
};
on: (key: emitKey, fn: func) => void = (key, fn) => {
// register
this.list[key] = this.list[key] || [];
this.list[key].push(fn);
};
private list: { [key: emitKey]: Array<func> } = {};
}
export default new Bus();
标签:...,typescript,bus,void,args,emitKey,key,event,fn
From: https://www.cnblogs.com/azoux/p/16782946.html