@@ -65,6 +65,16 @@ function on (event, callback) {
6565 eventEmitters . get ( this ) . on ( event , callback )
6666}
6767
68+ /**
69+ * Remove event listener function
70+ *
71+ * @param {String } event - Event name
72+ * @param {Function } callback - Callback function
73+ */
74+ function off ( event , callback ) {
75+ eventEmitters . get ( this ) . removeListener ( event , callback )
76+ }
77+
6878/**
6979 * Close the connection
7080 */
@@ -659,7 +669,24 @@ function sendMessage (message, recipient) {
659669 if ( typeof message === 'object' ) {
660670 info = JSON . stringify ( message )
661671 }
662- send ( this , { jsonrpc : '2.0' , method : 'channels.message' , params : { info, to : recipient } } )
672+ const doSend = ( channel ) => send ( channel , {
673+ jsonrpc : '2.0' ,
674+ method : 'channels.message' ,
675+ params : { info, to : recipient }
676+ } )
677+ if ( this . status ( ) === 'connecting' ) {
678+ const onStatusChanged = ( status ) => {
679+ if ( status !== 'connecting' ) {
680+ // For some reason we can't immediately send a message when connection is
681+ // established established. Thus we wait 500ms which seems to work.
682+ setTimeout ( ( ) => doSend ( this ) , 500 )
683+ this . off ( 'statusChanged' , onStatusChanged )
684+ }
685+ }
686+ this . on ( 'statusChanged' , onStatusChanged )
687+ } else {
688+ doSend ( this )
689+ }
663690}
664691
665692async function reconnect ( options , txParams ) {
@@ -724,6 +751,7 @@ const Channel = AsyncInit.compose({
724751 } ,
725752 methods : {
726753 on,
754+ off,
727755 status,
728756 state,
729757 id,
0 commit comments