实现一个EventEmitter类,这个类包含以下方法: on/ once/fire/off

实现一个EventEmitter类,这个类包含以下方法: on(监听事件,该事件可以被触发多次)- once(也是监听事件,但只能被触发一次)- fire(触发指定的事件)- off(移除指定事件的某个回调方法或者所有回调方法)
function EventEmitter() {
    this.handlers = {}
}
//监听事件,该事件可以被触发多次
EventEmitter.prototype.on = function (eventName, handle) {
    if (!this.handlers.hasOwnProperty(eventName)) {
        this.handlers[eventName] = []
    }
    this.handlers[eventName].push(handle)
}
//也是监听事件,但只能被触发一次
EventEmitter.prototype.once = function (eventName, handle) {
    
}
//触发指定的事件
EventEmitter.prototype.fire = function (eventName, ...params) {
    if (!this.handlers.hasOwnProperty(eventName)) return
    //事件队列依次执行
    this.handlers[eventName].map(handle => {
        handle(...params)
    })
}
//移除指定事件的某个回调方法或者所有回调方法
EventEmitter.prototype.off = function (eventName, handle) {
    if (!this.handlers.hasOwnProperty(eventName)) return
    //获取下标,并删除
    let index = this.handlers[eventName].indexOf(handle)
    this.handlers[eventName].splice(index, 1)
}

const emitter = new EventEmitter();
emitter.on('drink', (person) => {
console.log(person + '喝水')
})
emitter.on('eat', (person) => {
console.log(person + '吃东西')
})
// event.once('buy', (person) => {
// console.log(person + '买东西')
// })
emitter.fire('drink', '我') // 我喝水
emitter.fire('drink', '我') // 我喝水
emitter.fire('eat', '其它人') // 其它人吃东西
emitter.fire('eat', '其它人') // 其它人吃东西
emitter.fire('buy', '其它人') //其它人买东西
emitter.fire('buy', '其它人') //这里不会再次触发buy事件,因为once只能触发一次
emitter.off('eat') //移除eat事件
emitter.fire('eat', '其它人') //这里不会触发eat事件,因为已经移除了

  

转载于:https://www.cnblogs.com/yz-blog/p/11312596.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值