首页 > 其他 > 详细

实现原生on off tigger once 方法

时间:2019-09-22 15:41:24      阅读:125      评论:0      收藏:0      [点我收藏+]

最近听到别人面试,很多次考到了这种题目,今天整理了一下笔记,看到就整理出来大家一起学习,有什么不对的请指教。

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)
    }
}

基本实现了功能,多多指教

实现原生on off tigger once 方法

原文:https://www.cnblogs.com/xyc5258/p/11566751.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!