ES6 项目如何在任意地方拿到 WebScoket 消息?

除了将WebSocket实例挂在window对象下这样以外的方式。

编辑

eventEmitter.ts

import EventEmitter from 'events';

/**
 * Instantiate EventEmitter
 */
export default new EventEmitter();

baseWebSocket.ts

import ee from '~lib/eventEmitter';

/**
 * Base WebSocket
 */
export default class BaseWebSocket extends WebSocket {
    constructor(url: string, protocols: any) {
        super(url, protocols);
    }
    onopen = () => {
        ee.emit('ws:open');
    }
    onmessage = (message: any) => {
        const data = JSON.parse(message.data);
        ee.emit('ws:message', data);
    }
    onerror = (event: any) => {
        ee.emit('ws:error', event);
    }
    onclose = (event: any) => {
        ee.emit('ws:close', event);
    }
    onSend(data: any) {
        this.send(JSON.stringify(data));
    }
}

socketMiddleware.ts

import BaseWebSocket from '~lib/baseWebSocket';
import ee from '~lib/eventEmitter';
import { receivedMessages } from '~app/socketSlice';

export default function createSocketMiddleware (url: string) {
    return (store: any) => {
        let chatWs: BaseWebSocket;

        const onMessage = (data: any) => {
            store.dispatch(receivedMessages(data));
        }

        return (next: any) => (action: any) => {
            switch (action.type) {
                case 'socket/connect': {
                    chatWs = new BaseWebSocket(`${url}?clientId=${action.payload}`);
                    ee.on('ws:message', onMessage);
                    break;
                }
                case 'socket/close': {
                    chatWs.close();
                    break;
                }
                case 'socket/sendMessages': {
                    chatWs.onSend(action.payload);
                    break;
                }
            }
            return next(action);
        }
    }
}
阅读 1.7k
1 个回答

发布订阅,onmessage 收到消息之后发布出去,想用的地方订阅就好了。

  1. 使用 window.addeventListener
  2. vue 的话有 bus 之类的东西
  3. 可以自己 '@antv/event-emitter' 实现一个
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏