JS实现订阅发布

83 阅读1分钟

实现简单的发布订阅
1.首先维护一个类
2.添加监听事件的方法,给类中添加event元素,event元素用于储存给某一事件名添加的回调函数的数组,调用该方法将回调函数添加到指定事件名的数组中
3.触发事件的方法 检索指定事件名所对应的数组,并且遍历触发数组的每一项函数
4.解绑事件的方法 过滤指定事件名所对应的数组,将指定的函数从事件对应的数组中剔除

上代码

class EventListen{
    constructor(){
        this.events = {};
    }

    //创建监听方法,给同名的事件绑定监听函数的数组
    on(type, callback){
        this.events[type] = this.events[type] || [];
        this.events[type].push(callback);
    }

    //触发事件的方法
    emit(type, ...arg){
        this.events[type] = this.events[type] || [];
        for(listener of this.events[type]){
            listener(...arg);
        }
    }

    //解绑方法,从指定的事件的函数组中过滤指定函数完成解绑
    off(type, callback){
        this.events[type] = this.events[type] || [];
        this.events[type] = this.events[type].filter(item => item !== callback)
    }


}

const e = new EventListen();

//给click绑定监听函数
const callback = function(arg){
    console.log('click的监听函数', arg);
}
e.on('click',callback)

//触发click事件
e.emit(click, {id:'传入的入参会进入监听函数中'});

//进行事件的解绑
e.off('click', callback)