Fix: Make event listener setup idempotent and modularize connection logic

Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
This commit is contained in:
2025-09-01 12:14:24 +09:00
parent a0f5a1e372
commit 6b87c7b0c4
2 changed files with 33 additions and 13 deletions

View File

@@ -13,11 +13,19 @@ import { debounce, isMobile } from './utils.js';
// A flag to track if charts have been initialized
let chartsInitialized = false;
let listenersAttached = false;
/**
* Sets up all event listeners for the application's interactive elements.
* This function is now idempotent and will only attach listeners once.
*/
export function setupEventListeners() {
if (listenersAttached) {
console.log("Event listeners already attached. Skipping.");
return;
}
console.log("Attaching event listeners...");
// --- Theme Toggle ---
dom.themeToggle.addEventListener('change', () => {
const newTheme = dom.themeToggle.checked ? 'dark' : 'light';
@@ -90,4 +98,7 @@ export function setupEventListeners() {
// --- Window Resize Event ---
// Debounced to avoid excessive calls during resizing.
window.addEventListener('resize', debounce(ui.handleResize, 150));
listenersAttached = true;
console.log("Event listeners attached successfully.");
}

View File

@@ -46,7 +46,7 @@ function onWsClose() {
term.write('\r\n\x1b[31mConnection closed. Reconnecting...\x1b[0m\r\n');
}
// Attempt to re-establish the connection after 2 seconds
setTimeout(initialize, 2000);
setTimeout(connect, 2000);
}
/**
@@ -75,9 +75,26 @@ function onWsMessage(event) {
// --- Application Initialization ---
/**
* Establishes the connection-related parts of the application.
* Fetches initial status and initializes WebSocket.
*/
function connect() {
// Fetch initial status on page load or reconnect
updateControlStatus();
// Establish the WebSocket connection with the defined handlers
initWebSocket({
onOpen: onWsOpen,
onClose: onWsClose,
onMessage: onWsMessage
});
}
/**
* Initializes the entire application.
* This function sets up the UI, theme, terminal, chart, WebSocket connection, and event listeners.
* This function sets up the UI, theme, terminal, and event listeners.
* It should only be called once when the DOM is loaded.
*/
function initialize() {
// Initialize basic UI components
@@ -87,22 +104,14 @@ function initialize() {
setupTerminal();
// Apply the saved theme or detect the user's preferred theme.
// This must be done AFTER the chart and terminal are initialized.
const savedTheme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
applyTheme(savedTheme);
// Fetch initial status on page load
updateControlStatus();
// Establish the WebSocket connection with the defined handlers
initWebSocket({
onOpen: onWsOpen,
onClose: onWsClose,
onMessage: onWsMessage
});
// Attach all event listeners to the DOM elements
setupEventListeners();
// Start the connection process
connect();
}
// --- Start Application ---