我仍在尝试掌握回调的窍门。有人可以解释为什么我不能使用来自的回调更新我的网页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
,然后将套接字传递给函数。这可能吗?