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


全部评论

相关推荐

07-25 11:12
重庆大学 C++
既然这么缺人,为什么挂我呢
希望被offer砸中...:其实不缺人
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-24 13:39
在记录秋招的大魔王很...:别被忽悠了,我做了多年销售。我可以告诉你,这就是忽悠你的,销售一定要看底薪也要看提成两者不可缺一。提成是有业绩的时候才拿的到的,谁能保证一直有单状态都好。销售有时候很讲究运气的。底薪是你这个人这个岗位日常工作体现的价值。别小看底薪,你看那些跳槽去做经理主管的,底薪底一些,人家愿意去吗?所以那些说销售靠提成的纯属忽悠,除非他们的业务很容易成单。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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