如何使用html按钮创建动态的socket.join(socket.room)

时间:2018-07-01 16:54:34

标签: javascript socket.io

考虑一下,我们有3个HTML按钮,但是ID相同

<button id="id1"> John </button>
<button id="id1"> Peter </button>
<button id="id1"> williams </button>

这是我的socket.io脚本(客户端)

 $(document).on("click", "id1", function() {
  var ButtonText = $(this).text();
  var logged_in_userName ="i am using this application";
  var currentRoom = logged_in_userName + "-" + ButtonText;
  var reverseRoom = ButtonText + "-" + logged_in_userName;

//event to set room and join.
  socket.emit('set-room', {
  name1: currentRoom,
  name2: reverseRoom
  });
  });

服务器端脚本

socket.on('set-room', function (room) {
        //setting room and join.
        setRoom = function (roomId) {
            socket.room = roomId;
            socket.join(socket.room);
        };
    });

我的情况:

如果我单击按钮1,则john的socket.join()也需要发生,其他按钮也应具有相应的名称

1 个答案:

答案 0 :(得分:0)

并不清楚您要加入的房间名称到底是什么,但是您做错了几件事。首先,您要在事件处理程序中定义一个函数,然后再不调用该函数。然后,您无法正确访问随set-room消息发送的数据。

如果您希望reverseRoom属性是新加入的会议室的属性,则将服务器代码更改为此:

socket.on('set-room', function (data) {
    // since socket.room only stores one room name, I assume you want to leave
    // any prior room before overwriting that property
    if (socket.room) {
        socket.leave(socket.room);
    }
    socket.join(data.reverseRoom);
    socket.room = data.reverseRoom;
});