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.