实现原生on off tigger once 方法

最近听到别人面试,很多次考到了这种题目,今天整理了一下笔记,看到就整理出来大家一起学习,有什么不对的请指教。
class Event {
    constructor() {
        this.handlers = {}
    }
    on(type, handler, once=false){
        if(!this.handlers[type]){
            this.handlers[type] = []
        }
        if(!this.handlers[type].includes(handler)){
            this.handlers[type].push(handler)
            handler.once = once
        }
    }
    tigger(type,eventData={},point=this){
        if(this.handlers[type]){
            this.handlers[type].forEach(f => {
                f.call(point, eventData)
                if(f.once){
                    this.off(type,f)
                }
            })
        }
    }
    off(type, handler){
        if(this.handlers[type]){
            if(handler === undefined){
                this.handlers[type] = []
            }else{
                this.handlers[type] = this.handlers[type].filter(
                    f => f != handler
                )
            }
        }
    }
    once(type, handler){
        this.on(type, handler, true)
    }
}


全部评论

相关推荐

数学转码崽:一直给我推,投了又不理,理了又秒挂
点赞 评论 收藏
分享
01-26 18:45
门头沟学院 Java
一天代码十万三:哥们实习再包一下吧,产出太笼统了,尽量体现业务
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务