nodejs events模块

var EventEmitter = require('events').EventEmitter;

var emitter = new EventEmitter();

console.log(emitter.getMaxListeners());
//设置可监听事件的最大个数
emitter.setMaxListeners(11);

function work(who){
    console.log(who + ' go to work')
}

//监听事件
emitter.on('do', work);
emitter.on('do', function(who) {
    console.log(who + ' wash clothers')
});

emitter.on('rest', function(who) {
    console.log(who + ' can have a rest');
})

//移除监听事件
emitter.removeListener('do', work);

//触发事件
emitter.emit('do', 'John');
emitter.emit('do', 'lily');
emitter.emit('rest', 'Tom');

//所有‘do’的监听事件
console.log(emitter.listeners('do'))

//监听事件的个数
console.log(emitter.listenerCount('do'));

 

你可能感兴趣的:(nodejs events模块)