46 lines
941 B
TypeScript
46 lines
941 B
TypeScript
import mitt from 'mitt';
|
|
|
|
type IEventbus = {
|
|
clear: () => void;
|
|
publish: (eventName: string, content: any) => void;
|
|
subscribe: (eventName: string, callback: (content: any) => void) => void;
|
|
};
|
|
|
|
const emitter = mitt();
|
|
|
|
/**
|
|
* @description: 发布事件
|
|
* @param {*} eventName 事件名称
|
|
* @param {*} content 事件内容
|
|
*/
|
|
const publish = (eventName: string, content: any) => {
|
|
emitter.emit(eventName, content);
|
|
};
|
|
|
|
/**
|
|
* @description: 订阅事件
|
|
* @param {*} eventName 事件名称
|
|
* @param {*} callback 回调的函数
|
|
*/
|
|
const subscribe = (eventName: string, callback: (content: any) => void) => {
|
|
emitter.on(eventName, (content) => callback(content));
|
|
};
|
|
|
|
/**
|
|
* 清空所有的事件,避免多组件互相清理
|
|
*/
|
|
const clear = () => {
|
|
emitter.all.clear();
|
|
};
|
|
|
|
/**
|
|
* @description: 导出useEventbus
|
|
*/
|
|
export const useEventbus = (): IEventbus => {
|
|
return {
|
|
publish,
|
|
subscribe,
|
|
clear,
|
|
};
|
|
};
|