Skip to content
Advertisement

Attach an event handler to an object literal

I have an object literal to open a websocket connection. this is a simplified version of it:

const ws = {

    conn : null,

    start : function(){
            
            this.conn = new WebSocket('wss://.....');

            this.conn.onopen = (e) => {};   

            this.conn.onmessage = (e) => {};    
                
            this.conn.onclose = (e) => {};  
                    
        }
}

i can initialize the connection with:

var websocket = ws.start();

now i want to attach an eventhandler to websocket, which is called when onmessage is fired. like this:

websocket.on('message', function (e) {

    console.log('this.conn.onmessage in ws was fired');

});

is there a way to achieve this?

Advertisement

Answer

Just return the connection at the end of the start function.

const ws = {

    conn : null,

    start : function(){
            
            this.conn = new WebSocket('wss://.....');

            this.conn.onopen = (e) => {};   

            this.conn.onmessage = (e) => {};    
                
            this.conn.onclose = (e) => {};  
                    
            return this.conn;
        }
}
Advertisement