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


全部评论

相关推荐

05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
asdasdasda...:19岁,不容易啊可能升个本会好点,现在学历歧视太严重了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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