var EventEmitter = require('events').EventEmitter
var xx = new EventEmitter()
xx.setMaxListeners(11) //设置最大监听数量,超过的会报错(溢出),默认为10
xx.on('eventName',function)// 监听事件
xx.emit('eventName',参数)//响应监听事件,
xx.removeAllListeners() //移除xx.所有监听
xx.removeAllListeners('eventName') //移除xx.所有eventName监听
x.listeners('eventName').length //xx的eventName监听数量
EventEmitter.listenerCount(xx, 'eventName')//同上,xx的eventName监听数量
【实例】
代码:
var EventEmitter = require('events').EventEmitter
var life = new EventEmitter()
life.setMaxListeners(11)
function fun1(who){
console.log(who+'1');
}
life.on('a',fun1)
life.on('a',function(who){
console.log(who+'2');
})
life.on('a',function(who){
console.log(who+'3');
})
life.on('a',function(who){
console.log(who+'4');
})
life.on('a',function(who){
console.log(who+'5');
})
life.on('a',function(who){
console.log(who+'6');
})
life.on('a',function(who){
console.log(who+'7');
})
life.on('a',function(who){
console.log(who+'8');
})
life.on('a',function(who){
console.log(who+'9');
})
life.on('a',function(who){
console.log(who+'10');
})
life.on('a',function(who){
console.log(who+'11');
})
var hasAListener = life.emit('a','zdy');
console.log("初始是否被监听:"+ hasAListener);
console.log("初始监听数量:" + life.listeners('a').length);
life.removeListener('a',fun1); //移除监听
hasAListener = life.emit('a','zdy');
console.log("移除一个监听之后的监听数量:"+life.listeners('a').length);
console.log("移除一个监听之后是否被监听:"+ hasAListener);
life.removeAllListeners('a'); //移除全部监听
hasAListener = life.emit('a','zdy');
console.log("移除全部监听之后的监听数量:"+life.listeners('a').length);
console.log("移除所有监听之后是否被监听:"+ hasAListener);
console.log(EventEmitter.listenerCount(life, 'a'));
结果:
zdy1
zdy2
zdy3
zdy4
zdy5
zdy6
zdy7
zdy8
zdy9
zdy10
zdy11
初始是否被监听:true
初始监听数量:11
zdy2
zdy3
zdy4
zdy5
zdy6
zdy7
zdy8
zdy9
zdy10
zdy11
移除一个监听之后的监听数量:10
移除一个监听之后是否被监听:true
移除全部监听之后的监听数量:0
移除所有监听之后是否被监听:false
0