node概念笔记之eventemitter
1、产生事件分发的对象都是eventemitter的实例
2、events模块只提供一个对象events.EventEmitter,核心就是事件触发和事件监听功能的封装
引入方式
//引入events模块 var events = require('events'); //创建eventEmitter对象 var eventEmitter = new events.EventEmitter();
EventEmitter对象如果在实例化时发生错误,会触发error事件,当添加新的监听器时newListener事件触发,移除时removeListener事件被触发
//event.js文件 var EventEmitter = require('events').EventEmitter; var event = new EventEemitter(); event.on('some_event',function(){ console.log('some_event 事件触发') }); setTimeOut(function(){ event.emit('some_event'); },1000)
一秒后触发some_event,然后监听到这个事件的分发
支持若干事件监听器,顺序执行,事件参数作为会掉函数的参数传递
var events = require('events'); var emitter = new events.EventEmitter(); emitter.on('someEvent',function(arg1,arg2){ console.log('listener1',arg1,arg2); }); emitter.on('someEvent',function(arg1,arg2){ console.log('listener2',arg1,arg2); }); emitter.emit('someEvent',arg1,arg2);
下面是是EventEmitter的属性介绍
1、addListener(event,listener)
2、on(event,listener)//回调函数
3、once,单次事件监听,触发后立即解除
4、removeListener
5、removeAllListeners
6、setMaxListeners
7、listeners返回执行事件的监听器数组
8、emit,按参数执行每个监听器
实例
var events = require('events'); var eventEmitter = new events.EventEmitter(); //监听器#1 var listener1 = function listener1(){ console.log('监听器Listener1执行') } //监听器#2 var listener2 = function listener2(){ console.log('监听器Listener2执行') } eventEmitter.addListener('connect',listener1); eventEmitter.addListener('connect',listener2); var eventListeners = require('events').EventEmitter.EventEmitterCount(eventEmitter,'connect'); console.log(evnetListeners+'个监听器监听连接事件'); eventEmitter.emit('connect'); // 移除监绑定的 listener1 函数 eventEmitter.removeListener('connection', listener1); console.log("listener1 不再受监听。"); // 触发连接事件 eventEmitter.emit('connection'); eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection'); console.log(eventListeners + " 个监听器监听连接事件。"); console.log("程序执行完毕。");
error事件
继承EventEmitter