@@ -35,6 +35,7 @@ class Codebolt {
3535 websocket : WebSocket | null = null ;
3636 private isReady : boolean = false ;
3737 private readyPromise : Promise < void > ;
38+ private readyHandlers : Array < ( ) => void | Promise < void > > = [ ] ;
3839
3940 /**
4041 * @constructor
@@ -56,6 +57,15 @@ class Codebolt {
5657 this . websocket = cbws . getWebsocket ;
5758 this . isReady = true ;
5859 console . log ( "Codebolt WebSocket connection established" ) ;
60+
61+ // Execute all registered ready handlers
62+ for ( const handler of this . readyHandlers ) {
63+ try {
64+ await handler ( ) ;
65+ } catch ( error ) {
66+ console . error ( 'Error executing ready handler:' , error ) ;
67+ }
68+ }
5969 } catch ( error ) {
6070 console . error ( 'Failed to initialize WebSocket connection:' , error ) ;
6171 throw error ;
@@ -106,6 +116,31 @@ class Codebolt {
106116 utils = cbutils ;
107117 notify = notificationFunctions ;
108118
119+ /**
120+ * Sets up a handler function to be executed when the WebSocket connection is established.
121+ * If the connection is already established, the handler will be executed immediately.
122+ * @param {Function } handler - The handler function to call when the connection is ready.
123+ * @returns {void }
124+ */
125+ onReady ( handler : ( ) => void | Promise < void > ) {
126+ if ( this . isReady ) {
127+ // If already ready, execute the handler immediately
128+ try {
129+ const result = handler ( ) ;
130+ if ( result instanceof Promise ) {
131+ result . catch ( error => {
132+ console . error ( 'Error in ready handler:' , error ) ;
133+ } ) ;
134+ }
135+ } catch ( error ) {
136+ console . error ( 'Error in ready handler:' , error ) ;
137+ }
138+ } else {
139+ // If not ready yet, add to the list of handlers to execute when ready
140+ this . readyHandlers . push ( handler ) ;
141+ }
142+ }
143+
109144 /**
110145 * Sets up a listener for incoming messages with a direct handler function.
111146 * @param {Function } handler - The handler function to call when a message is received.
0 commit comments