node.js中的回调函数.TypeError: Cannot call method 'emit'的定
Callback function in node.js. TypeError: Cannot call method 'emit' of undefined
我还在试着掌握回调的窍门。有人能解释为什么我不能更新我的网页使用回调从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
调用它,然后将套接字传递给函数。这可能吗?
您将socket
作为参数,但setInterval
不将参数传递给其回调*。只需利用包含作用域中的socket
:
setInterval(function() { // Remove socket
socket.emit('leftPingStatus', {status: _leftPing});
socket.emit('rightPingStatus', {status: _rightPing});
}
, 50);
你不能在其他地方定义这个函数;你需要一个函数来返回这个函数或者一个接受socket
的函数,例如
setInterval(function() {
doSomething(socket);
}
, 50);
相关文章:
- call()和apply()实际上是用来欺骗方法处理类似数组的对象的
- document.applet.method在Mounatin Lion上抛出safari 6+JDK7异常
- 当method=post时,jQueryAjax返回404
- Xml : Cannot call method 'getElementsByTagName' of n
- Rails和React: TypeError: Cannot call method 'map'的定义
- node.js中的回调函数.TypeError: Cannot call method 'emit'的定
- 错误:TypeError: Cannot call method 'replace'的定义
- 错误:TypeError: Cannot call method 'replace'的定义
- Google Script: TypeError: Cannot call method "createEve
- Node.js TypeError: Cannot call method 'write' of und
- xmlReader Failed with: TypeError: Cannot call method 'te
- TypeError: Cannot call method 'toFixed'的未定义,JavaScri
- 如何解决“Cannot call method 'stream'”undefined"
- 未捕获的TypeError: Cannot call method 'download'的定义
- 查询返回控制台日志中的项目,但是html显示Uncaught TypeError: Cannot call method
- 为什么使用这个obj.method.call(obj,arg)而不是obj.method(arg)
- KnockoutJS fromJS not working TypeError: Cannot call method
- Google Maps JS: Uncaught TypeError: Cannot call method '
- 未捕获的TypeError: Cannot call method 'shift'null - all.
- UncaughtTypeError:Cannot call method 'getElementByTagNam