1

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!

Stan Loona
  • 615
  • 9
  • 18

1 Answers1

2

It seems like you want to create a singleton

You can do that by exporting a version of your socket object that everything will share:

class Socket {
    constructor(ip) {
        this.socket = io(ip);
    }

    sendMessage(message, data) {
        this.socket.emit(message, data);
    }
}

export default new Socket('some_ip');

Then in your code you can do:

import s from "./multiplayer/Socket.js";

s.socket.on('something', doSomething);

and every place you import that socket object it will share all of the same information

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 1
    Thanks! Although I modified it a bit, added a new function on the class that returns this.socket and then I've been using like Socket.getSocket().on("message", function); – Stan Loona Dec 19 '19 at 01:10