/*
* @Author: Jackie
* @Date: 2023-07-31 17:43:19
* @LastEditTime: 2023-07-31 20:40:14
* @LastEditors: Jackie
* @Description: eventbus封装 类方式
* @FilePath: /vue3-utils-demo/src/utils/EventBus.js
* @version:
*/
class Event {
constructor() {
this.queue = {};
this.onceQueue = {};
}
$on(name, callback) {
this.queue[name] = this.queue[name] || [];
this.queue[name].push(callback);
}
$once(name, callback) {
this.onceQueue[name] = this.onceQueue[name] || [];
this.onceQueue[name].push(callback);
}
$off(name, callback) {
if (callback) {
if (this.queue[name]) {
for (var i = 0; i < this.queue[name].length; i++) {
if (this.queue[name][i] === callback) {
this.queue[name].splice(i, 1);
break;
}
}
}
} else {
delete this.queue[name];
}
}
$emit(name, data) {
if (this.queue[name]) {
this.queue[name].forEach(function (callback) {
callback(data);
});
}
if (this.onceQueue[name]) {
this.onceQueue[name].forEach(function (callback) {
callback(data);
});
delete this.onceQueue[name];
}
}
}
export default new Event();
// 使用
// import Bus from '@/utils/EventBus';
// Bus.$on('test', (data) => {})
// Bus.$emit('close')
// beforeUnmount() {
// Bus.$off('test', fun)
// }