1

Here is my code that is not working:

connectSocket: function () {
  this.socket = new WebSocket('ws://144.0.0.0:8080'); //IP Changed
  this.socket.onopen = function(event) {
    console.log("Connected to the Web Socket Server");
    this.socket.send("Opponent has joined.");
    };
    alert("You're now connected to the server. Be careful out there.");
  this.socket.onmessage = function(event) {
    console.log("Message Received From Server :", event);
    //This is the time to interact with this specific
  };
}

The code I am referencing is a method in my vue called upon authentication. I am merely trying to send and receive basic data to the Web Socket Server. However somewhere this is flawed... How could I fix this and maintain authentication?

1 Answer 1

3

Your event handlers are losing context (this) when declared. Use arrow functions to preserve the current context, so the this there references the Vue instance:

connectSocket: function () {
  this.socket = new WebSocket('ws://144.0.0.0:8080'); //IP Changed
  this.socket.onopen = (event) => {               // changed to arrow function
    console.log("Connected to the Web Socket Server");
    this.socket.send("Opponent has joined.");

    alert("You're now connected to the server. Be careful out there.");
  };
  this.socket.onmessage = (event) => {              // changed to arrow function
    console.log("Message Received From Server :", event);
    //This is the time to interact with this specific
  };
}

Also it seemed you had unbalanced curly brackets, so I changed them too. But the important part is really the use of arrow functions.

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

1 Comment

Thanks! This is just what I needed,I don't quite understand it but looked it up here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . Does the => work because it doesn't have its own "this" whereas if I create a new function that function it has its own "this" associated to it so the parent "this" won't work?

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.