简体   繁体   中英

Storing data for global access without global variable

I am making a node.js game server and I am using socket.io for webscockets and rooms. However this is mostly a pure JavaScript question:

I am creating a room with a random number for every 2 players, and it works like this:

  • A random room number is generated and stored globally;
  • A player joins the room
  • If he is the second player in this room, a new room number is generated and the next player joins the next random number room

     var openRoom = Math.floor(Math.random() * 90000) + 10000; io.sockets.on('connection', function (socket) { socket.on('addPlayer', function(username) { if (io.sockets.clients(openRoom).length <= 2) { socket.join(openRoom); } else { openRoom = Math.floor(Math.random() * 90000) + 10000; socket.join(openRoom); } ... 

    Is there a way not to use the global openRoom ?

  • You need to use a closure so that the openRoom variable is exposed to the inner functions.

    For example:

    (function() {
    
    var openRoom = Math.floor(Math.random() * 90000) + 10000;
    
    io.sockets.on('connection', function (socket) {
    
        socket.on('addPlayer', function(username) {
    
            if (io.sockets.clients(openRoom).length <= 2)  {
                socket.join(openRoom);
            } else {
                openRoom = Math.floor(Math.random() * 90000) + 10000;
                socket.join(openRoom);
            }
    ...
    
    })();
    

    You could also create a global object with which to store any of your globals in:

    if (typeof window['MyApp'] == 'undefined') {
    
        MyApp = {
            someVar: someValue
        };
    
    }
    

    This lets you get/set it later:

    var x = MyApp.someVar;
    

    Look at datastore solutions like Redis.io. They are designed for these sort of transient things, to help you not clutter your code with globals, while being performant enough to not noticeably slow things down.

    With redis, you would simply call a function that updates the key in redis with a new value.

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM