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

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

问题描述

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

On the first click, my client outputs this:

Object {hello: "world"} 

然后在第二次点击时:

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

并且每次点击输出该行的次数随着后续点击增加1次.

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

推荐答案

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

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天全站免登陆