38 lines
898 B
JavaScript
38 lines
898 B
JavaScript
class EventManager {
|
|
constructor() {
|
|
this.eventMap = {};
|
|
}
|
|
/**
|
|
* 注册事件
|
|
* @param {string} eventName - 事件名称
|
|
* @param {function} callback - 事件回调函数
|
|
*/
|
|
on(eventName, callback) {
|
|
if (!this.eventMap[eventName]) {
|
|
this.eventMap[eventName] = [];
|
|
}
|
|
this.eventMap[eventName].push(callback);
|
|
}
|
|
/**
|
|
* 触发事件
|
|
* @param {string} eventName - 事件名称
|
|
* @param {...any} args - 事件参数
|
|
*/
|
|
emit(eventName, ...args) {
|
|
if (this.eventMap[eventName]) {
|
|
this.eventMap[eventName].forEach(callback => callback(...args));
|
|
}
|
|
}
|
|
/**
|
|
* 移除事件
|
|
* @param {string} eventName - 事件名称
|
|
* @param {function} callback - 事件回调函数
|
|
*/
|
|
off(eventName, callback) {
|
|
if (this.eventMap[eventName]) {
|
|
this.eventMap[eventName] = this.eventMap[eventName].filter(cb => cb !== callback);
|
|
}
|
|
}
|
|
}
|
|
export default new EventManager();
|