Reputation: 113
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);
});
});
Upvotes: 4
Views: 1869
Reputation: 298196
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'
});
});
Upvotes: 4