zoukankan      html  css  js  c++  java
  • 简单的事件处理类Event

    class Event{
        constructor(){
            this.handlers=[]
        }
        on(type,fn){  //订阅事件  
            if(!this.handlers[type]){
                this.handlers[type] = [];
            }
            this.handlers[type].push({handle:fn,one:false});
        }
        one(type,option={},fn){ //订阅只执行一次的事件
            if(!this.handlers[type]){
                this.handlers[type] = [];
            }
            this.handlers[type].push({handle:fn,one:true});
        }
        emit(type,option,fn){ //发布某类事件或者某个事件,fn存在时候只执行订阅过的fn事件
            var handlers = this.handlers[type]
            for (var i=0, len=handlers.length; i < len; i++){
                if(fn){
                    if(handlers[i].handle === fn){
                        handlers[i].handle(option)
                        if(handlers[i].one){
                            handlers.splice(i, 1);
                        }
                        break;
                    }
                }else {
                    handlers[i].handle(option)
                    if(handlers[i].one){
                        handlers.splice(i, 1);
                    }
                }
    
            }
        }
        remove(type,fn){  //移除某类事件或者某个事件,fn存在即移除该事件
            var handlers = this.handlers[type]
            if(fn){
                for (var i=0, len=handlers.length; i < len; i++){
                    if(handlers[i] === fn){
                        handlers.splice(i, 1);
                        break;
                    }
                }
            }else {
                delete this.handlers[type];
            }
        }
    }
    export default new Event();
    

      

  • 相关阅读:
    navicat for mysql (本人亲测,真实有效)
    python 8 days
    python 19 days
    python 20 days
    python 21 days
    python 10 days
    python 9 days
    python 14 days
    python 15 days
    python 16 days
  • 原文地址:https://www.cnblogs.com/jiebba/p/7263256.html
Copyright © 2011-2022 走看看