JS事件中心

作者: WebGiser | 来源:发表于2022-05-11 21:57 被阅读0次

    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();
    

    相关文章

      网友评论

        本文标题:JS事件中心

        本文链接:https://www.haomeiwen.com/subject/cdejurtx.html