1.Node中的事件模块
Node的事件模块只包含了一个类:EventEmitter。
这个类在node的内置模块和第三方模块中大量使用。
EventEmitter,用于监听一些事件,并且处理,本质上是一个观察者模式的实现
2.EventEmitter基本使用方式
const events = require('events')
const emitter = new events.EventEmitter()
function fn1(name){
console.log("fn1",name)
}
function fn2(name){
console.log("fn2",name)
}
emitter.on('say', fn1)
emitter.on('say', fn2)
emitter.emit('say','Tom')
emitter.removeListener('say', fn1)
emitter.emit('say','jerry')
3.自己实现一个EventEmitter类
class myEventEmitter{
constructor(){
this.events = {}
}
on(eventName, callback){
if(!this.events){
this.events = {}
}
if(!this.events[eventName]){
this.events[eventName] = []
}
this.events[eventName].push(callback)
}
emit(eventName, ...rest) {
if(this.events[eventName]){
this.events[eventName].forEach((listener)=>listener.apply(this,rest))
}
}
removeListener(eventName, listener){
if (this.events[eventName]){
this.events[eventName] = this.events[eventName].filter(item=>item!=listener)
}
}
}
let myEmitter = new myEventEmitter()
function fn1(name){
console.log("fn1",name)
}
function fn2(name){
console.log("fn2",name)
}
myEmitter.on('say', fn1)
myEmitter.on('say', fn2)
myEmitter.emit('say','Tom')
myEmitter.removeListener('say', fn1)
myEmitter.emit('say','jerry')