From fe249db5dd48dab30debb966d6d057b60ed0b0b5 Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Sat, 8 Oct 2022 15:46:00 +0800 Subject: [PATCH] feat: add useGlobalSocketEvent --- client/shared/api/socket.ts | 12 ++++++++++ client/web/src/plugin/common/index.ts | 5 ++++- client/web/src/utils/global-state-helper.ts | 25 ++++++++++++++++++++- client/web/tailchat.d.ts | 5 +++++ 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/client/shared/api/socket.ts b/client/shared/api/socket.ts index b991623e..8b2d8ab6 100644 --- a/client/shared/api/socket.ts +++ b/client/shared/api/socket.ts @@ -67,6 +67,18 @@ export class AppSocket { this.listener.push([`notify:${eventName}`, callback as any]); } + /** + * 移除监听函数 + */ + removeListener(eventName: string, callback: (data: any) => void) { + const index = this.listener.findIndex( + (item) => item[0] === eventName && item[1] === callback + ); + if (index >= 0) { + this.listener.splice(index, 1); + } + } + /** * 模拟重连 * NOTICE: 仅用于开发环境 diff --git a/client/web/src/plugin/common/index.ts b/client/web/src/plugin/common/index.ts index 301fa02f..d111c8f3 100644 --- a/client/web/src/plugin/common/index.ts +++ b/client/web/src/plugin/common/index.ts @@ -20,7 +20,10 @@ export { openReconfirmModal, } from '@/components/Modal'; export { Loadable } from '@/components/Loadable'; -export { getGlobalState } from '@/utils/global-state-helper'; +export { + getGlobalState, + useGlobalSocketEvent, +} from '@/utils/global-state-helper'; export { getJWTUserInfo } from '@/utils/jwt-helper'; export { dataUrlToFile } from '@/utils/file-helper'; export { diff --git a/client/web/src/utils/global-state-helper.ts b/client/web/src/utils/global-state-helper.ts index a2ef7d9e..af8ce4a3 100644 --- a/client/web/src/utils/global-state-helper.ts +++ b/client/web/src/utils/global-state-helper.ts @@ -1,4 +1,5 @@ -import type { AppStore, AppState, AppSocket } from 'tailchat-shared'; +import { useEffect } from 'react'; +import { AppStore, AppState, AppSocket, useMemoizedFn } from 'tailchat-shared'; let _store: AppStore; export function setGlobalStore(store: AppStore) { @@ -22,3 +23,25 @@ export function getGlobalSocket(): AppSocket | null { } return _socket; } + +/** + * 获取全局socket并监听 + */ +export function useGlobalSocketEvent( + eventName: string, + callback: (data: T) => void +) { + const fn = useMemoizedFn(callback); + + useEffect(() => { + if (_socket) { + _socket.listen(eventName, fn); + } + + return () => { + if (_socket) { + _socket.removeListener(eventName, fn); + } + }; + }, []); +} diff --git a/client/web/tailchat.d.ts b/client/web/tailchat.d.ts index f7d54660..e377c7bd 100644 --- a/client/web/tailchat.d.ts +++ b/client/web/tailchat.d.ts @@ -72,6 +72,11 @@ declare module '@capital/common' { export const getGlobalState: any; + export const useGlobalSocketEvent: ( + eventName: string, + callback: (data: T) => void + ) => void; + export const getJWTUserInfo: () => Promise<{ _id?: string; nickname?: string;