0

我仍在尝试掌握回调的窍门。有人可以解释为什么我不能使用来自的回调更新我的网页setInterval吗?

当我运行代码时,我得到了错误

/home/pi/Programming/RC Car/server_serialport.js:32
      socket.emit('leftPingStatus', {status: _leftPing});
             ^
TypeError: Cannot call method 'emit' of undefined
    at null.<anonymous> (/home/pi/Programming/RC Car/server_serialport.js:32:14)
    at wrapper [as _onTimeout] (timers.js:252:14)

我的代码:

var express = require('express');
var app = express()
    ,server = require('http').createServer(app)
    ,io = require('socket.io').listen(server)
    ,wire = require('i2c')
    ,sys = require('sys')
    ,exec = require('child_process').exec;

//Web page status
var _connected = false;
var _leftPing = 0;
var _rightPing = 0;

//SERVER
server.listen(9081, 'raspberrycar.local');
app.use(express.static(__dirname + '/public'));

//SOCKET.IO
io.sockets.on('connection', function (socket){
    _connected = true; //Connected
    socket.emit('serverStatus', {   status: 'Server Connected' }); //Client connected
    socket.emit('arduinoStatus', {   status: 'Arduino Connected' }); //Arduino connected
    socket.on('key', KeyReceived);  //Key received from client
    setInterval(transferData, 50); //Transfer data to/from arduino

    //THIS DOES NOT WORK
    setInterval(function (socket){
        socket.emit('leftPingStatus', {status: _leftPing});
        socket.emit('rightPingStatus', {status: _rightPing});
    }
    , 50) //Transfer data to/from webpage
});

io.sockets.on('disconnect', function (socket){
    _connected = false; //Connected
});

我宁愿单独定义我的函数,从中调用它setInterval,然后将套接字传递给函数。这可能吗?

4

1 回答 1

4

您将socket其作为参数,但setInterval不会将参数传递给它的回调*。只需利用socket包含范围内的 :

setInterval(function() { // Remove socket
    socket.emit('leftPingStatus', {status: _leftPing});
    socket.emit('rightPingStatus', {status: _rightPing});
}
, 50);

本质上,您无法在其他地方真正定义该功能;你需要一个函数来返回这个函数或一个接受的函数socket,例如

setInterval(function() {
    doSomething(socket);
}
, 50);
于 2013-06-15T16:32:10.317 回答