🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 写一个EventEmitter类,包括on()、off()、once()、emit()方法 ``` // 写一个EventEmitter类,包括on()、off()、once()、emit()方法 class EventEmitter { constructor() { this.handlers = {} } on (type, fn) { if (!this.handlers[type]) { this.handlers[type] = [] } this.handlers[type].push(fn) return this } off (type, fn) { const fns = this.handlers[type]; for (let i = 0; i < fns.length; i++) { if (fns[i] == fn) { fns.splice(i, 1); break; } } return this } once (type, fn) { const warp = (...args) => { fn.apply(this, args) this.off(type, warp) } this.on(type, warp) return this } emit () { const args = [...arguments] const type = args[0] const params = args.slice(1) this.handlers[type].forEach(f => { f.apply(this, params) }); return this } } var e1 = new EventEmitter() function fun1 () { console.log('fun1'); } function fun2 () { console.log('fun2'); } function fun3 () { console.log('fun3'); } e1.on('TEST1',fun1).on('TEST2',fun2).emit('TEST1').once('TEST2',fun3); e1.emit("TEST2"); ```