/** * Chahua Development Thailand * บริษัทชาหัวประเทศไทย * CEO: Saharath C. * www.chahuadev.com * chahuadev@gmail.com * * /** * HUB - Central Event Hub (Pub/Sub System) V.11.0.0 * * ศูนย์กลางการสื่อสารระหว่างโมดูลทั้งหมดในแอปพลิเคชัน * ทำงานในรูปแบบ Publish/Subscribe เพื่อลดการพึ่งพากัน (Decoupling) * * Features: * on(event, fn): ลงทะเบียนเพื่อ "ฟัง" เหตุการณ์ * emit(event, data): "ส่ง" เหตุการณ์ออกไปให้ผู้ฟังทั้งหมด * once(event, fn): ลงทะเบียนฟังเหตุการณ์แค่ครั้งเดียวแล้วลบออก * off(event, fn): ยกเลิกการฟังเหตุการณ์ * emitAsync(event, data): emit แบบรอให้ callback ที่เป็น async ทำงานจนเสร็จ * Wildcard Listener ('*'): ดักฟังทุกเหตุการณ์ที่เกิดขึ้นใน Hub * * by Chahuadev Studio V.11.0.0 Enterprise Architecture */ class CallbackHub { constructor() { this.handlers = {}; this.debug_mode = process.env.HUB_DEBUG === 'true' || false; console.log(' Event Hub initialized - Pub/Sub System V.11.0.0'); } /** * ลงทะเบียนฟังก์ชัน (callback) เพื่อรอฟังเหตุการณ์ (event) * @param {string} eventName - ชื่อเหตุการณ์ที่ต้องการฟัง (เช่น 'license.loaded' หรือ '*' เพื่อฟังทุกอย่าง) * @param {Function} callback - ฟังก์ชันที่จะถูกเรียกใช้เมื่อมีเหตุการณ์เกิดขึ้น */ on(eventName, callback) { if (!this.handlers[eventName]) { this.handlers[eventName] = []; } this.handlers[eventName].push(callback); if (this.debug_mode) { console.log(` Hub: Listener registered for "${eventName}" (${this.handlers[eventName].length} total)`); } } /** * ลงทะเบียนฟังก์ชันเพื่อรอฟังเหตุการณ์แค่ "ครั้งเดียว" * หลังจากทำงานเสร็จ callback จะถูกลบออกไปโดยอัตโนมัติ * @param {string} eventName - ชื่อเหตุการณ์ * @param {Function} callback - ฟังก์ชันที่จะถูกเรียกใช้ */ once(eventName, callback) { const onceWrapper = (data) => { callback(data); this.off(eventName, onceWrapper); if (this.debug_mode) { console.log(` Hub: Once listener for "${eventName}" executed and removed`); } }; this.on(eventName, onceWrapper); } /** * ยกเลิกการลงทะเบียน callback * @param {string} eventName - ชื่อเหตุการณ์ * @param {Function} callback - ฟังก์ชันที่ต้องการยกเลิก */ off(eventName, callback) { if (this.handlers[eventName]) { const initialLength = this.handlers[eventName].length; this.handlers[eventName] = this.handlers[eventName].filter(cb => cb !== callback); if (this.debug_mode && this.handlers[eventName].length < initialLength) { console.log(` Hub: Listener removed from "${eventName}" (${this.handlers[eventName].length} remaining)`); } } } /** * ส่งสัญญาณ (emit) เหตุการณ์ออกไป * จะเรียก callback ทุกตัวที่ลงทะเบียนไว้กับ event นี้แบบ non-blocking * @param {string} eventName - ชื่อเหตุการณ์ * @param {*} [data] - ข้อมูลที่ต้องการส่งไปกับเหตุการณ์ */ emit(eventName, data) { let listenersNotified = 0; // ส่งให้ผู้ฟังที่เจาะจง event นี้ if (this.handlers[eventName]) { this.handlers[eventName].forEach(fn => { try { fn(data); listenersNotified++; } catch (err) { console.error(` Hub: Callback error on "${eventName}":`, err); } }); } // ส่งให้ผู้ฟังแบบ Wildcard ('*') ด้วย if (this.handlers['*']) { this.handlers['*'].forEach(fn => { try { fn({ event: eventName, data: data }); listenersNotified++; } catch (err) { console.error(` Hub: Wildcard callback error on "${eventName}":`, err); } }); } if (this.debug_mode) { console.log(` Hub: Event "${eventName}" emitted to ${listenersNotified} listener(s)`); } } /** * ส่งสัญญาณ (emit) เหตุการณ์และรอให้ callback ที่เป็น async ทำงานจนเสร็จ * @param {string} eventName - ชื่อเหตุการณ์ * @param {*} [data] - ข้อมูลที่ต้องการส่งไปกับเหตุการณ์ * @returns {Promise} */ async emitAsync(eventName, data) { const promises = []; // ผู้ฟังที่เจาะจง event if (this.handlers[eventName]) { this.handlers[eventName].forEach(fn => { promises.push(Promise.resolve().then(() => fn(data)).catch(err => { console.error(` Hub: Async callback error on "${eventName}":`, err); })); }); } // ผู้ฟังแบบ Wildcard ('*') if (this.handlers['*']) { this.handlers['*'].forEach(fn => { promises.push(Promise.resolve().then(() => fn({ event: eventName, data: data })).catch(err => { console.error(` Hub: Async wildcard callback error on "${eventName}":`, err); })); }); } if (this.debug_mode) { console.log(` Hub: Async event "${eventName}" emitted to ${promises.length} listener(s)`); } await Promise.all(promises); } /** * แสดงรายชื่อ event ทั้งหมดที่มีการลงทะเบียนไว้ */ debug() { console.log(' Hub: Registered Event Handlers:'); for (const eventName in this.handlers) { console.log(` - ${eventName} (${this.handlers[eventName].length} listener(s))`); } const totalEvents = Object.keys(this.handlers).length; const totalListeners = Object.values(this.handlers).reduce((sum, handlers) => sum + handlers.length, 0); console.log(` Hub: Total ${totalEvents} events, ${totalListeners} listeners`); } /** * เปิด/ปิด debug mode * @param {boolean} enabled - เปิดหรือปิด debug mode */ setDebugMode(enabled) { this.debug_mode = enabled; console.log(` Hub: Debug mode ${enabled ? 'ENABLED' : 'DISABLED'}`); } /** * ลบ listeners ทั้งหมดของ event หนึ่งๆ * @param {string} eventName - ชื่อเหตุการณ์ที่ต้องการลบ listeners */ removeAllListeners(eventName) { if (this.handlers[eventName]) { const count = this.handlers[eventName].length; delete this.handlers[eventName]; if (this.debug_mode) { console.log(` Hub: Removed all ${count} listeners for "${eventName}"`); } } } /** * ลบ listeners ทั้งหมด */ removeAll() { const eventCount = Object.keys(this.handlers).length; this.handlers = {}; console.log(` Hub: Removed all listeners (${eventCount} events cleared)`); } } // สร้างและ Export เป็น Singleton Instance เพื่อให้ทุกไฟล์ได้ใช้ตัวเดียวกัน module.exports = new CallbackHub();