vue3+ts发布订阅模式


此次项目在写即时通讯的时候需要使用到发布订阅模式,一下在记录下项目中使用的方法

1.创建ts文件夹,写如下代码

class EventListenControl {
    container: any = {};//创建对象
    on(evt: string, callback: Function) {//订阅(evt:需要监听的字段,callback:方法)
        if (!this.container[evt]) this.container[evt] = [];
        this.container[evt].push(callback);//每一次订阅,将键和方法存入对象中
    }
    emit(evt: string, ...arg: any[]) {//发布
        if (this.container.hasOwnProperty(evt))//在对象中找对应的键
            this.container[evt].forEach((fn: Function) => {//调用对象中的方法返回数据
                fn(...arg);
            })
    }
    remove(evt: string, callback: Function) {//销毁当前订阅
        if (this.container[evt] && this.container[evt] instanceof Array) {
            let idx = this.container[evt].findIndex((el: Function) => el == callback);
            if (idx >= 0) {
                this.container[evt].splice(idx, 1);
            }
        }
    }
}

export default EventListenControl;

2.在websocket中数据返回时,根据返回的字段进行信息发布

ws.onmessage = (event) => {//接收websocket回传数据
      let data = JSON.parse(event.data);//数据结构成对象
      this.emit(data.key, data.content);//data.key就是订阅传入的evt,data.content为数据
}

3.项目中使用,项目中引入第一步ts文件

//订阅
ws.on("chat", receiveMessage);//"chat"为约定字段,这里代指聊天,receiveMessage为方法

//回调方法,消息接收
const handleReceiveMessage = (res: any) => {//websocket返回的数据这里只接受类型为chat的

};