Nodejs socket.io chat room, when the chat button is clicked, emit will be triggered many times.

when I click the chat button for the first time, one event is triggered, the second click triggers two events, and so on

server code:

    socket.on("chat",function(data){
        io.sockets.emit("chat",data);
    });

client code:

$(document).off("click.chatBtn").on("click.chatBtn",".chatBtn",function(e){
        var $target = $(e.currentTarget);
        var $charInput = $target.siblings(".charInput");
        var val = $charInput.val();
        var userName = $userName.val();
        if(!userName){
            alert("");
            return;
        }
        socket = io.connect();
        socket.emit("chat",userName+" speak:"+val);
        socket.on("chat",function(data){
            var $it = addMsg(data);
            $it.appendTo($message);
        });
    });

Mar.20,2021

move this code out of the click function and try it.

        socket.on('chat',function(data){
            var $it = addMsg(data);
            $it.appendTo($message);
        });
For more information, please see https://stackoverflow.com/que.

.
Menu