function EventEmitter(){
this.message = {}
}
EventEmitter.prototype.on = function(type,fn){
if(!this.message[type]){
this.message[type] = [fn]
}else{
this.message[type].push(fn)
}
}
EventEmitter.prototype.emit = function(type,...args){
if(!this.message[type]) return
this.message[type].forEach(item=>{
item.apply(this,args)
})
}
EventEmitter.prototype.remove = function(type,fn){
if(!this.message[type]) return
if(!fn) this.message[type] = []
for(let i=this.message[type].length-1;i>=0;i--){
this.message[type][i] === fn && this.message[type].splice(i,1)
}
}
EventEmitter.prototype.once = function(type,fn){
const callback = (...args) => {
fn.apply(this,args)
this.remove(type,callback);
}
this.on(type,callback)
}
let event = new EventEmitter()
function age(...age){
console.log('hello,今年我' + age)
}
event.on('getAge',age)
event.emit('getAge',24) //hello,今年我24
event.emit('getAge',25) //hello,今年我25
event.once('getName',function(...name){ console.log('hello,' + name) })
event.emit('getName','lisan','李三') //hello,lisan,李三
event.emit('getName', '赵四') //空
event.remove('getAge')
//ES6类实现
class EventEmitter{
constructor() {
this.message = {}
}
on(type,fn){
if(!this.message[type]){
this.message[type] = [fn]
}else{
this.message[type].push(fn)
}
}
emit(type,...args){
if(!this.message[type]) return
this.message[type].forEach((item)=>{
item.apply(this,args)
})
}
off(type,fn){
if(!this.message[type]) return
if(!fn) this.message[type] = []
for(let i=this.message[type].length-1;i>=0;i--){
this.message[type][i] == fn && this.message[type].splice(i,1)
}
}
once(type,fn){
let callback = (...args)=>{
fn.apply(this,args)
this.off(type,callback)
}
this.on(type,callback)
}
}
手写一个发布-订阅模式EventEmitter
最新推荐文章于 2024-06-20 01:27:45 发布