node 事件原理

对象中封装事件对应的各个函数,调用时遍历对象中的函数
let fs =require('fs');

fs.readFile("C:/Users/10853/Desktop/tt.txt",{flag:'r',encoding:"utf-8"},function(err,data){
	console.log(data);
	jeEvent.emit('ok',data);
})


var jeEvent={
	event:{
		
	},//存入事件
	on:function(name,fun){
		//如果event中有函数名,则放方法
		if(this.event[name])
		{
			this.event[name].push(fun);

		}else{
			this.event[name]=[];
			this.event[name].push(fun);

		}
	},
	//事件触发
	emit:function(name,data)
	{
		if(this.event[name]){

			this.event[name].forEach(function(item,index){
				item(data);
			})
		}
	}
}

jeEvent.on('ok',function(eventMsg){
	console.log('1');
})
jeEvent.on('ok',function(eventMsg){
	console.log('2');
})
jeEvent.on('ok',function(eventMsg){
	console.log('3');
})
发布了534 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/104792391