Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js javascript modules on client side

Node.js javascript modules on client side

Problem

I'm writing a game using node.js+express+socket.io. It took a long time to get where I am but i feel it finally got me. I have server which servs html and js files in this way:

app.post('/game', function(req, res) {
     handleGame(req, res); //it opens file using fs and forwards with res.end(readFile);
});

app.get('/scripts/*', function(req, res) {
     handleStatic(req, res); //same schema
});

And now, I'm logged and on site game.html (received from first app.post). It loaded fine, initRight is changed to 'bbbb', If I open 'source code' in firefox, I can click and see both player.js and game.js source code. Hovewer, inside init() Function of game.js module, there should be change to initRight field again to 'AAAAA', but as I can see Player function from player module is invisible inside game module (I've detected that when I was moving socket.io handlers to different module). I'm doing that in this way because I've seen it in different project and I really don't want next overwhelm with putting some require.js to get require() function etc. My question is should it work? If yes why it might not here?

Problem courtesy of: aragornsql

Solution

While your question is confusing and I don't see the connection with NodeJS for your question, the problem is that your JavaScript has mutliple issues.

I copied your code to JSBin:

http://jsbin.com/iqudic/4/edit (and live: http://jsbin.com/iqudic/4)

Then, I cleaned it up a little bit.

You likely would want to put the associated attributes on the instance of the Player object rather than returning them as a new object like you were.

var Player = function(playerNick, playerId, playerSocket) {
  this.nick = playerNick;
  this.id = playerId;
  this.socket = playerSocket;
};

Secondly, and this was causing the AAAAAA to not appear:

function init() {
    // socket and socket.id should be defined before creating the Player
    localPlayer = new Player('AAAAAA', socket.id, socket);
    document.getElementById('initRight').innerHTML = localPlayer.nick;
}

Your code assumes that there is a socket.id and socket object available within the init function. It's crashing on that line. You should always take a look at the Console window of your favorite web browser.

socket is not defined

Solution courtesy of: WiredPrairie

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js javascript modules on client side

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×