- 新建onfire.ts文件
export interface Listener {
cb: Function;
once: boolean;
}
export interface EventsType {
[eventName: string]: Listener[];
}
export default class OnFire {
static ver = "__VERSION__";
es: EventsType = {};
on(eventName: string, cb: Function, once: boolean = false) {
if (!this.es[eventName]) {
this.es[eventName] = [];
}
this.es[eventName].push({
cb,
once,
});
}
once(eventName: string, cb: Function) {
this.on(eventName, cb, true);
}
fire(eventName: string, ...params: any[]) {
const listeners = this.es[eventName] || [];
let l = listeners.length;
for (let i = 0; i < l; i++) {
const { cb, once } = listeners[i];
cb.apply(this, params);
if (once) {
listeners.splice(i, 1);
i--;
l--;
}
}
}
off(eventName?: string, cb?: Function) {
if (eventName === undefined) {
this.es = {};
} else if (cb === undefined) {
delete this.es[eventName];
} else {
const listeners = this.es[eventName] || [];
let l = listeners.length;
for (let i = 0; i < l; i++) {
if (listeners[i].cb === cb) {
listeners.splice(i, 1);
i--;
l--;
}
}
}
}
emit(eventName: string, ...params: any[]) {
this.fire(eventName, ...params);
}
}
- 新建eventBus.ts
import EE from "./onfire";
export const EVENT_AUTO_LAYOUT = "AUTO_LAYOUT";
export default new EE();
- 新建ts文件导出useEventBus
interface UseEventType {
type: string;
onChange: any;
}
export const useEventBus = ({ type, onChange }: UseEventType, dep = []) => {
useEffect(() => {
eventBus.on(type, onChange);
return () => {
eventBus.off(type, onChange);
};
}, [type, onChange, dep]);
};
- 使用
import eventBus from "./eventBus";
eventBus.emit("ROLE_TAG", roleTag);
import { useEventBus } from "./utils/auth";
useEventBus({type: "ROLE_TAG", onChange: useCallback((name) =>{
setTags(name);
}, []),
});