实现原生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)
    }
}


全部评论

相关推荐

Twilight_m...:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务