Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  67] [ 3]  / answers: 1 / hits: 131764  / 12 Years ago, mon, july 2, 2012, 12:00:00

I'm working on a Node.js app (it's a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the proper room.



Right now, it's being done like this with Express v2.5.8:



server.get(/room/:name/:roomId, function (req, res) {
game = ~databaseLookup~
res.render(board, { gameState : game.gameState });
}


Over in board.ejs I can access the gameState manner with code like this:



<% if (gameState) { %>
<h2>I have a game state!</h2>
<% } %>


Is there a way for me to import this into my JavaScript logic? I want to be able to do something like var gs = ~import ejs gameState~ and then be able to do whatever I want with it--access its variables, print it out to console for verification. Eventually, what I want to do with this gameState is to display the board properly, and to do that I'll need to do things like access the positions of the pieces and then display them properly on the screen.



Thanks!


More From » node.js

 Answers
26

You could directly inject the gameState variable into javascript on the page.



<% if (gameState) { %>
<h2>I have a game state!</h2>
<script>
var clientGameState = <%= gameState %>
</script>
<% } %>


Another option might be to make an AJAX call back to the server once the page has already loaded, return the gameState JSON, and set clientGameState to the JSON response.



You may also be interested in this: How can I share code between Node.js and the browser?


[#84533] Friday, June 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;