nodeJs---emitter模块(模拟封装)
class EventEmitter { constructor() { this.emitter = {} } on(eventName,cb) { if (this.emitter[eventName]) { this.emitter[eventName].push(cb) } else { this.emitter[eventName] = [] this.emitter[eventName].push(cb) } } emit(eventName,...str) { if (this.emitter[eventName]) { for (let item of this.emitter[eventName]) { item(...str) } } else { throw eventName + 'is not definde'; } } } const eventEmitter = new EventEmitter(); const connectHandler = (str,str1) => { console.log('连接成功1。'+str,str1); eventEmitter.emit('data_received'); } eventEmitter.on('connection', connectHandler); eventEmitter.on('connection', (str,str1) => { console.log('连接成功2。'+str,str1); }); eventEmitter.on('data_received', () =>{ console.log('数据接收成功。') }); eventEmitter.emit('connection','teststr','xxxxxx'); console.log('程序执行完毕。')