Search code examples
javascriptarraysnode.jssocket.ionode.js-domains

node.js defining same array for each room different


As I said at title, I want to define a different array for each room. For example:

For room1, array will be var colors=['red','blue'],

for room2, array will be var colors=['black','white']. (Same name but different content)

Here is my simplified server:

var io = require('socket.io').listen(3000).set('log level', 2);

io.sockets.on('connection', function (socket) {
    var room = socket.handshake.query.room;  // room1 -- ws://localhost:3000/?room=room1

    socket.join(r); // add client to 'room1' room.
    // var colors = ['yellow','green'];
    io.sockets.in(r).emit('m', colors);
}

I don't want something like if(h=='room1') { var colors=['a','b'];} elseif(room=='room2') { var colors=['y','z']; } because there will be a lot of rooms.

How can I achive this? Should I use namespaces instead of rooms?


Solution

  • Then have an object with room names as keys, with corresponding arrays. Then use the current room name to automatically get the color array from the color list:

    var colorList = {
          'room1' : ['a','b'],
          'room2' : ['y','z']
        }
      , colors = colorList[room]
      ;