创建一个事件处理的订阅发布类
/* * @Descripttion: * @version: 1.1.1 * @Author: 张三 * @Date: 2021-07-21 15:12:54 * @LastEditors: 李四 * @LastEditTime: 2021-07-21 15:58:56 */class Event{ constructor(){ } //存放所有绑定的事件 handlers = {} //处理器 //给事件添加方法,参数type:事件名 handler:事件处理函数 addEventListener(type,handler){ //判断是否存在该事件 if(!(type in this.handlers)){ this.handlers[type] = []; } //将事件处理函数添加到该事件处理函数列表内 this.handlers[type].push(handler); } //触发事件的方法 type:事件名 payload:参数 dispatchEvent(type,...payload){ if(!(type in this.handlers)){ return new Error('此事件不存在') } this.handlers[type].forEach(handler => handler(...payload)); } //删除事件上的方法 removeEventListener(type,handler){ if(!(type in this.handlers)){ return new Error('此事件不存在'); } if(!handler){ //不存在handler,默认删除此事件的全部事件处理函数,也就是删除这个事件 delete this.handlers[type]; return '事件绑定移除成功'; } //找出该事件处理函数在事件函数列表的位置 let ind = this.handlers[type].findIndex(item => item === handler); //判断是否存在该事件 if(!ind){ return new Error('不存在此事件处理函数'); } //移除事件 this.handlers[type].splice(ind,1); //判断事件处理函数列表是否不为空,为空删除该事件 if(!(this.handlers[type].length)){ delete this.handlers[type]; return '事件绑定移除成功'; } return '事件处理函数移除成功'; }}
类的使用
var event = new Event() // 创建event实例// 定义一个自定义事件:"load"function load (params) { console.log('load', params)}event.addEventListener('load', load)// 再定义一个load事件function load2 (params) { console.log('load2', params)}event.addEventListener('load', load2)// 触发该事件event.dispatchEvent('load', 'load事件触发')// 移除load2事件event.removeEventListener('load', load2)// 移除所有load事件event.removeEventListener('load')