1

I try to use the following code to connect a Websocket:

var sConn = {
    socket: null,
    uri: "ws://" + window.location.host + "/socket/",

    init: function() { 
        this.socket = new WebSocket(this.uri);
        this.socket.onopen = this.onOpen;
        this.socket.onclose = this.onClose;
        this.socket.onerror = this.onError;
        this.socket.onmessage = this.onMessage;
    },


    onOpen: function(){
        console.log(this.socket); // prints "undefined"
        this.socket.send("Hello Server!"); // can't read property send of undefined
    },
    onClose: function(event){
         console.log("Close:",event); // is never called
    },
    onError: function(err){
        console.log("Error:",err); // also never called
    },
    onMessage: function(msg){
        console.log("Got Message:",msg);
    }
};
$(document).ready(function(){
    sConn.init();
});

unfortunately when onOpen is called socket seems to be undefined. I first thought maybe the socket is closed right after onOpen, but onClose is never called and onError is also never called.

What is my mistake?

1 Answer 1

1

You're losing the binding context in init().

Try rewriting it to this:

init: function() { 
  this.socket = new WebSocket(this.uri);
  this.socket.onopen = this.onOpen.bind(this);
  this.socket.onclose = this.onClose.bind(this);
  this.socket.onerror = this.onError.bind(this);
  this.socket.onmessage = this.onMessage.bind(this);
}

This makes sure that all the event handler functions in sConn are run with the correct this context.

Alternatively, you can refer to the socket with sConn.socket instead of this.socket.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.