【NodeJS】学习之EventEmitter

1.first: 某一个事件
2.点on一次,就是为某个事件注册一个 【事件监听器】;
3.同一个事件,可以注册多个事件监听器;
4.当事件被触发(emit)时,注册到这个事件的所有事件监听器会被依次调用,事件参数作为emit回调函数的参数

代码:

//events: events模块
var events = require('events')

//EventEmitter: events模块的一个对象或类
//emitter:EventEmitter的实例
var emitter = new events.EventEmitter();

// first: 某一个事件
// 点on一次,就是为某个事件注册一个 【事件监听器】;
// 同一个事件,可以注册多个事件监听器;
// 当事件被触发(emit)时,注册到这个事件的所有事件监听器会被依次调用,事件参数作为emit回调函数的参数;
emitter.on('first', function (a, b) {
    console.log('listener1', a, b)
})
emitter.on('first', function (a, b) {
    console.log('listener2', a, b)
})
emitter.on('first', function (a, b) {
    console.log('listener3', a, b)
})

emitter.emit('first', '大宝', '二宝')
console.log('程序执行完毕')

打印结果:

E:\Math\nodeProject\firstDemo>node event.js
listener1 大宝 二宝
listener2 大宝 二宝
listener3 大宝 二宝
程序执行完毕

猜你喜欢

转载自blog.csdn.net/Jerryman_GHJ/article/details/82776472