Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
Custom Class Event Handling

I am trying to teach myself about JavaScript classes.

My code is the following...

class Multiplayer {
  constructor(url, port) {
    this.socket = new WebSocket("ws://" + url + ":" + port);
    this.opponentReady = false;
    this.ready = false;
    this.recvEventMsg = "receivedMessage";

    // Create the events for the socket connection
    this.openConnection();
    this.receivedMessage();
  }

  closeConnection() {
    // Typically this will be called when either the game is over or when the user
    // no longer wants to play.
    this.socket.close();
  }

  getCustomEventName() {
    return this.recvEventMsg;
  }

  openConnection() {
    this.socket.addEventListener("open", (event) => {
      console.log("Sent to the opponent: Let's play!");
      this.socket.send("Let's play");
      this.opponentReady = true;
      this.ready = true;
    });
  }

  // The send message function should allow for communication
  // between players as well as notifying the other player
  // if a special event occurs via the 'status'.
  // Example, msg = "i made a  move here", status = 200
  // Example, msg = "Player X wins", status = 100
  // Maybe status == 100 could mean shut down the connection?
  sendMessage(message, status) {
    const contents = {
      msg: message,
      status: status,
    };

    this.socket.send(contents);
    return true;
  }

  // My intention is to have an event to be called when a message
  // has been received from the server or another client.
  receivedMessage() {
    this.socket.addEventListener("message", (messageEvent) => {
      console.log("CLIENT SAID: " + messageEvent);

      // Trigger the custom event and pass the information to that.
      // Custom Event triggered here...
      // Don't know how to do this.
      // Something like...
      // const newEvent = new CustomEvent(this.recvEventMsg, {detail: {message: messageEvent}});
      // someSortOfObject.dispatchEvent(newEvent);
    });
  }
}

The trouble I am facing is how do I create a custom event within my class? Such that whoever instantiates the class needs to create an EventListener to receive the custom events within my class.

Objective is the following within a script...

const socketConnectionEvent = (eventMessage) => {
 console.log('Socket Event has been captured!');
 console.log('Player said: ' + eventMessage.detail.message);
}

let socketConnection = new Multiplayer('127.0.0.1', 8000);
socketConnection.addEventListener(socketConnection.getCustomEventName(), socketConnectionEvent);

My goal is create a class that I can re-use for not only this small game app I created but others as well. I know the WebSocket is basically a class in of itself, but I am trying to learn and practice how to make good classes in JavaScript.

Any advice or help would be greatly appreciated.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda