Files
vitfit-r2/V2/app/public/js/socket-client.js
T
2026-06-13 08:03:45 -04:00

67 lines
1.6 KiB
JavaScript

/* VitFit socket-client.js */
'use strict';
class SocketClient {
constructor() {
this._socket = null;
this._reconnectHandlers = [];
this._disconnectHandlers = [];
this._handlers = {};
this._currentRoom = null;
}
connect() {
if (this._socket?.connected) return;
const jwt = Auth.getJwt();
this._socket = io({ auth: { token: jwt }, reconnectionDelay: 1000, reconnectionDelayMax: 10000 });
this._socket.on('connect', () => {
if (this._currentRoom) this._socket.emit('timer:join', { sessionId: this._currentRoom });
this._reconnectHandlers.forEach(cb => cb());
});
this._socket.on('disconnect', (reason) => {
this._disconnectHandlers.forEach(cb => cb(reason));
});
// Re-bind registered handlers to new socket
Object.entries(this._handlers).forEach(([event, handler]) => {
this._socket.on(event, handler);
});
window._socketClient = this;
}
on(event, handler) {
this._handlers[event] = handler;
this._socket?.on(event, handler);
}
emit(event, data) {
this._socket?.emit(event, data);
}
joinRoom(sessionId) {
this._currentRoom = sessionId;
this._socket?.emit('timer:join', { sessionId });
}
leaveRoom(sessionId) {
this._currentRoom = null;
this._socket?.emit('timer:leave', { sessionId });
}
onDisconnect(cb) { this._disconnectHandlers.push(cb); }
onReconnect(cb) { this._reconnectHandlers.push(cb); }
destroy() {
this._socket?.disconnect();
this._socket = null;
this._handlers = {};
this._reconnectHandlers = [];
this._disconnectHandlers = [];
window._socketClient = null;
}
}