首页 > Web开发 > 详细

nodeJs---emitter模块(模拟封装)

时间:2018-05-14 23:31:50      阅读:182      评论:0      收藏:0      [点我收藏+]
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(‘程序执行完毕。‘)

  

nodeJs---emitter模块(模拟封装)

原文:https://www.cnblogs.com/kingkun/p/9038676.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!