自定义全局事件

472 阅读1分钟

原理

创建包含事件type及其回调函数列表callbackFn list、监听函数on、触发函数emit,然后全局共享该对象即可

实现

function commonEvent(){
    this.handlers = {};
    this.on = function(type,callback){
        this.handlers[type] = this.handlers[type]||[];
        this.handlers[type].push(callback);
    }
    this.emit = function(type,...args){
        if(this.handlers[type]){
            this.handlers[type].forEach(f=>f.apply(null,args));
        }
    }
}

扩展

利用函数原型及属性描述对象来冻结原生函数,防止篡改