JavaScript

JS事件中心

2022-05-11  本文已影响0人  WebGiser

JS事件中心:事件监听、事件分发、事件销毁。

// 事件中心
class Bus{
    constructor(){
        // 收集订阅消息,调度中心
        this.list = {};
    }

    // 事件订阅
    $on(name, fn){
        this.list[name] = this.list[name] || [];
        this.list[name].push(fn);
    }

    // 事件发布
    $emit(name, data){
        if(this.list[name]){
            this.list[name].map((fn)=>{
                fn(data);
            })
        }
    }

    // 事件取消订阅
    $off(name){
        if(this.list[name]){
            delete this.list[name];
        }
    }
}

export default Bus;
// export default new Bus();
import Bus from Bus;
export default new Bus();
上一篇 下一篇

猜你喜欢

热点阅读