I'm trying to encapsulate socket.io inside a class, so I can share the same socket in multiple files (using import). This is the common way to use WebSockets if you are using only one file
Test.js
let ip = "http://localhost/";
let socket = io(ip);
socket.emit("message", {"content": "hello"});
socket.on("messageResponse", function(content) {
//Do something here.
});
What I'm trying to achieve is..
multiplayer/Socket.js
class Socket {
constructor(ip) {
this.socket = io(ip);
}
sendMessage(message, data) {
this.socket.emit(message, data);
}
}
export default Socket;
A.js
import Socket from "./multiplayer/Socket.js";
//listen to certain events here like socket.on("connect")
B.js
import Socket from "./multiplayer/Socket.js";
//listen to some other events here like socket.on("chatMessage")
But I don't know how to encapsule the on event. I'm using rollup to bundle the script inside one single file.
Thanks!