$(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.