# Node EventEmitter
观察者模式的体现
# Demo
// xxxService.js
const EventEmitter = require('events');
class MyService extends EventEmitter {
// ...
}
const myEmitter = new MyService();
myEmitter.on('event', callback);
module.exports = myEmitter;
// 别的地方引用,先require
myEmitter.emit('event'); // emit event
# 支持传参Demo
// xxxService.js
const EventEmitter = require('events');
class MyService extends EventEmitter {
emit(event, ...query) {
return super.emit(event, query);
}
}
const myEmitter = new MyService();
myEmitter.on('event', callback);
module.exports = myEmitter;
myEmitter.emit('event',[1,2,3,4,5]); // emit event