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!

1
  • So you want to create a singleton? Commented Dec 18, 2019 at 21:27

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.