挺直观的小example吧,放到文件里node一下,还是蛮有意思

/**
 * Created by Amy on 2017/7/13.
 */
var EventEmitter=require('events').EventEmitter
var life=new EventEmitter()
life.setMaxListeners(4)//系统默认最多不要超过十个,防止事件泄露
//addEventListener
function water(who){
    console.log('给'+who+'倒水')
}
life.on('求安慰',function(who)
)
life.on('求安慰',function(who){
    console.log('给'+who+'做饭')
})
life.on('求安慰',function(who){
    console.log('给'+who+'洗衣服')
})
life.on('求溺爱',function(who){
    console.log('给'+who+'买衣服')
})

//life.removeListener('求安慰',water)  //移除监听事件
//life.removeAllListener('求安慰')//妹子不开心了,要求全部移除
var hasConfortListener=life.emit('求安慰','汉子')
var hasLovedListener=life.emit('求溺爱','妹子')

console.log(life.listeners('求安慰').length)
console.log(life.listeners('求溺爱').length)
console.log(EventEmitter.listenerCount(life,'求安慰'))//这两个都可以打印出监听事件数目


console.log(hasConfortListener)
console.log(hasLovedListener)

  

posted on 2017-07-13 23:41  Amy鱼  阅读(209)  评论(0编辑  收藏  举报