jquery – socket.on事件每次响应都会重复多次

我成功融合后设置了socket.emit事件.但是当我绑定sockets.on事件时会出现问题.它被多次开除.

$(document).on('click','#comment_button',function() {
    $.ajax({
        // upon success
        success: function (response) {

            if (response) {
                socket.emit('postcomment');

                socket.on('refresh',function () {
                    console.log('refresh');
                  //This console.log('refresh') is coming multiple times. I mean its occurance increases with every successful ajax response.
                });
        }
    });
});

这是我的server.js

socket.on('postcomment',function () {
        io.sockets.emit("refresh");
});

我已经验证在我的server.js中,socket.on函数只被调用一次.
我不确定在ajax中socket.on(‘refresh’,function(){}有什么问题.
任何帮助都会很棒.

P.S socket connection is already made. No problem in that.

EDIT: I rectified the mistake. If anyone is reading this in future.
As jason and Niranjan mentioned,socket.on{} event was binding themselves upon successful response.
To be simple:
Every time the click handler is called,it attaches additional event listeners to the socket. The listeners you attached on the prevIoUs clicks remain active.

所以我对之前的代码进行了以下更改

$(document).on('click',function() {
    $.ajax({
        // upon success
        success: function (response) {

            if (response) {
                socket.emit('postcomment');

        }
    });
});

socket.on('refresh',function () {
    console.log('refresh');
});

快乐的编码.

解决方法

我对之前的代码进行了以下更改.
有效.

$(document).on('click',function () {
    console.log('refresh');
});

socket.on{} event was binding themselves upon successful response. To be simple: Every time the click handler is called,it attaches additional event listeners to the socket. The listeners you attached on the prevIoUs clicks remain active.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...