简体   繁体   中英

Callback function in node.js. TypeError: Cannot call method 'emit' of undefined

I'm still trying to get the hang of callbacks. Can someone explain why I cannot update my webpage using the callback from setInterval ?

When I run the code, I get the error

/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)

My code:

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

I would rather define my function separately, call it from setInterval and then pass the socket to the function. Is this possible?

You're taking socket as an argument, but setInterval doesn't pass arguments to its callback*. Just take advantage of the socket in the containing scope:

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

You can't really define that function elsewhere, per se; you would need a function to return this function or a function that accepts socket , eg

setInterval(function() {
    doSomething(socket);
}
, 50);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM