RylonMcnz RylonMcnz - 4 months ago 16
Javascript Question

Passing socket between multiple client side javascript files

I recently started coding a small web game in javascript. Even more recently, I started refactoring the code to use node.js with socket.io to make the game multiplayer.

My issue, which I cannot find a solution for, is that I would like to pass the client side socket variable to multiple client side javascript files.

In client/app.js:

var app = (function() {
...
var socket = io.connect('http://localhost:8080');
socket.on('connect', function() {
dice.setSocket(socket);
});
...
})();


In client/dice.js:

var dice = (function() {
...
var gameSocket;
if (gameSocket) {
gameSocket.on('dice rolling', function(data) {
playDiceAnim(data);
});
}
function setSocket(socket) {
gameSocket = socket;
}
})();


Unfortunately, when the 'dice rolling' event is emitted from the server side, playDiceAnim(data) is never executed. But, I know that the 'dice rolling' event is being received by app.js. For example, if in app.js I put:

var app = (function() {
...
var socket = io.connect('http://localhost:8080');
socket.on('dice rolling', function() {
console.log('event received');
});
...
})();


Then, the result in the developer tools console is:

'event received'


The examples that I can find online either put all client side javascript into a script tag in a .html file, or in a single .js file. But, I would like to be more modular than that.

How can I appropriately pass and use the client side socket to other client side files?

Here is the full code. Beware of bugs, it is in the process of being refactored. Also, any aside advice would be greatly appreciated as I am still fairly new to javascript and node.js.

Answer

Here's what I would suggest:

Load the app script first and have it make the socket available to other callers via a method:

var app = (function() { 
    ...
    var socket = io.connect('http://localhost:8080');

    return {
        getSocket: function() { return socket;}
    }
    ...
})();

var dice = (function() {
    ...
    var gameSocket = app.getSocket();
    if (gameSocket) {
        gameSocket.on('dice rolling', function(data) {
            playDiceAnim(data);
        });
    }
})();

In this case, I think it makes more sense for the app to be a provider of services such as a connected webSocket and for other modules to request that information from the app. But, it really depends upon which module you want to be more generic and not depend upon the other. It could go either way.

Comments