实现一个EventEmitter类:on(监听事件)- once(监听事件一次)- fire(触发指定的事件)- off(移除指定事件)

class EventEmitter {
    constructor() {
        this.queue = {} //可触发多次的事件
        this.onceQueue = {} //只能触发一次的事件
    }
    on(event, fn) {  //监听事件,可以触发多次
        if (!this.queue[event]) this.queue[event] = []
        this.queue[event].push(fn)
    }
    once(event, fn) {   //监听事件,只能触发一次
        if (!this.onceQueue[event]) {
            this.onceQueue[event] = {
                fns: [],
                hasFired: false
            }
        }
        this.onceQueue[event].fns.push(fn)
    }
    fire() {  //触发指定的事件
        const event = [].shift.call(arguments), //取得事件名称
            fns = this.queue[event],  //取得该事件里所有的回调函数(可以触发多次的事件)
            onceFns = this.onceQueue[event]  //取得该事件里所有的回调函数(只能触发一次的事件)
        if (fns && fns.length != 0) {
            let i = 0,fn
            while (fn = fns[i++]) {
                fn.apply(this, arguments)
            }
        }
        if (onceFns && !onceFns.hasFired) {
            let i = 0,fn
            while (fn = onceFns.fns[i++]) {
                fn.apply(this, arguments)
            }
            this.onceQueue[event].hasFired = true
        }
    }
    off(event, fn = null) { //可移除特定事件里的某个回调函数或者所有回调函数
        const fns = this.queue[event]
        if (!fns || fns.length == 0) return
        if (fn) { //移除该事件特定的回调
            this.queue[event] = fns.filter(item => {
                return item !== fn
            })
        } else { //移除该事件所有的回调
            this.queue[event] = []
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值