export default class EventDispatcher { constructor() { this.listeners = {} } /** * 添加事件监听器 * @param {string} type - 事件类型 * @param {Function} listener - 监听函数,当事件触发时会执行此函数 */ addEventListener(type, listener) { if (!this.listeners[type]) { this.listeners[type] = [] } // 检查监听函数是否已经存在于该事件类型的监听队列中,如果不存在则添加 if (this.listeners[type].indexOf(listener) === -1) { this.listeners[type].push(listener) } } /** * 根据事件类型移除所有的事件监听器 * @param {string} type - 事件类型 */ removeEventListener(type) { this.listeners[type] = [] } /** * 触发指定类型的事件,并向事件监听器传递数据 * @param {string} type - 事件类型 * @param {*} data - 要传递给事件监听器的数据 */ dispatchEvent(type, data) { const listenerArray = this.listeners[type] || [] if (listenerArray.length) { listenerArray.forEach((listener) => { listener.call(this, data) }) } } }