socket.on calls its callback too many times

2019-02-18 01:18发布

问题:

On the first click, my client outputs this:

Object {hello: "world"} 

Then on the second click:

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

And the number of times the line is output for a click increases by one with 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);
});
});

回答1:

You're binding a new event handler each time the click event handler is triggered. Bind it once 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'
    });
});