请实现EventEmitter, 让打印输出符合预期
const eventBus = new EventEmitter()
const eventBus1 = new EventEmitter()
console.log(eventBus === eventBus1) // 打印输出: true
function handleClick(param1, param2) {
console.log(param1, param2)
}
eventBus.on('click', handleClick)
eventBus.emit('click', 'foo', 'bar') // 打印输出: foo bar
function EventEmitterOrigin(){
this.fn='';//用于存触发之后的事件
this.name='click';
this.emit=(name,...arg)=>{
if(name==this.name){
this.fn(...arg)//用于发布触发存储的fn
}
}
this.on=(name,fn)=>{
this.name=name;
this.fn=fn;//用于订阅存储下fn
return this.fn
}
}
//单例模式只生成一个实例
let EventEmitter=(function(){
let fac='';
return function (){
if(!fac){
fac=new EventEmitterOrigin()
return fac
}
return fac
}
})()
// 请实现EventEmitter, 让打印输出符合预期
const eventBus = new EventEmitter()
const eventBus1 = new EventEmitter()
console.log(eventBus === eventBus1) // 打印输出: true
function handleClick(param1, param2) {
console.log(param1, param2)
}
eventBus.on('click', handleClick)
eventBus.emit('click', 'foo', 'bar') // 打印输出: foo bar