Estoy tratando de aprender sobre las clases de JavaScript.
mi codigo es el siguiente...
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); }); } }El problema al que me enfrento es ¿cómo creo un evento personalizado dentro de mi clase? De modo que quien crea una instancia de la clase necesita crear un EventListener para recibir los eventos personalizados dentro de mi clase.
El objetivo es el siguiente dentro de un 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);Mi objetivo es crear una clase que pueda reutilizar no solo para esta pequeña aplicación de juego que creé, sino también para otras. Sé que WebSocket es básicamente una clase en sí misma, pero estoy tratando de aprender y practicar cómo crear buenas clases en JavaScript.
Cualquier consejo o ayuda sería muy apreciada.