socket.on多次调用其回调 [英] socket.on calls its callback too many times

查看:522
本文介绍了socket.on多次调用其回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次点击,我的客户输出:

On the first click, my client outputs this:

Object {hello: "world"} 

然后第二次单击:

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

点击一次输出的行数随着点击的增加而增加一.

And the number of times the line is output for a click increases by one with subsequent click.

客户

var socket = io.connect('http://localhost');

$(document).on('click' , '#test', function(){
    socket.emit('news', { my: 'data' });
    socket.on('news', function (data) {
        console.log(data);
    });
});

服务器

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);
});
});

推荐答案

每次触发click事件处理程序时,您都将绑定一个新的事件处理程序.在回调之外将其绑定一次:

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'
    });
});

这篇关于socket.on多次调用其回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆