jq点击事件多次响应_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', '#comment_button', function() {

$.ajax({

// upon success

success: function (response) {

if (response) {

socket.emit('postcomment');

}

});

});

socket.on('refresh', function () {

console.log('refresh');

});

快乐的编码.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值