class MyEvent { constructor() { // 事件的数组 this.funcArray = []; } /** * 绑定事件 * @param funcName 事件名称 * @param cb 回调函数 */ on(funcName, cb) { this.funcArray.push({[funcName]: cb, funcName: funcName, once: false}); } /** * 触发方法 * @param funcName 方法明 * @param args 参数 */ emit(funcName, ...args) { this.funcArray.forEach((item, index) => { if (funcName === item.funcName) { // 执行方法 item[funcName](...args) if (item.once) this.funcArray.splice(index, 1) } }) } /** * 绑定一次性执行的参数 * @param funcName 事件名称 * @param cb 回调函数 */ once(funcName, cb) { this.funcArray.push({[funcName]: cb, funcName: funcName, once: true}) } /** * 移除事件 * @param funcName 事件名称 */ off(funcName){ let index = this.funcArray.findIndex(item => item.funcName === funcName); this.funcArray.splice(index, 1); } } const myEvent = new MyEvent(); myEvent.on('abacd', (a, b) => { console.log('abacd', a, b) }) myEvent.once('once13',(a, b)=>{ console.log('once13 只会执行一次', a, b) }) myEvent.emit('abacd', 123, 424) myEvent.off('abacd'); myEvent.emit('abacd', 123, 424) myEvent.emit('once13', 123, 424) myEvent.emit('once13', 123, 424)
结果: