Socket.on calls its callback too many times

At the first click, my client displays this:

Object {hello: "world"} 

Then on the second click:

 Object {hello: "world"} Object {hello: "world"} 

And the number of times a line is displayed on a click increases by one with a subsequent click.

Client

 var socket = io.connect('http://localhost'); $(document).on('click' , '#test', function(){ socket.emit('news', { my: 'data' }); socket.on('news', function (data) { console.log(data); }); }); 

Server

 var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') io.sockets.on('connection', function (socket) { socket.on('news', function (data) { socket.emit('news', { hello: 'world' }); console.log(data); }); }); 
+4
source share
1 answer

You bind a new event handler every time the click event handler starts. Bind it outside of the callback:

 var socket = io.connect('http://localhost'); socket.on('news', function(data) { console.log(data); }); $(document).on('click', '#test', function() { socket.emit('news', { my: 'data' }); }); 
+4
source

Source: https://habr.com/ru/post/1496430/


All Articles