无法从套接字连接外部定义的方法发出
我正在尝试使用自定义对象的方法来发送到套接字连接。该对象是在套接字连接外部定义的,但随后在其内部实例化。代码和错误如下。
app.js
...
io.sockets.on('connection', function (socket) {
report = new Report();
socket.on('dataChange', function(newData) {
report.update(newData);
});
});
function Report () {
this.update = function (data) {
socket.emit('updateReport', { data: data });
}
}
错误
节点给我以下错误。
socket.emit('updateReport', { data: data });
^参考错误:套接字未定义
I'm trying to use a custom object's method to emit to a socket connection. The object is defined outside of the socket connection, but then instantiated inside of it. Code and error follows.
app.js
...
io.sockets.on('connection', function (socket) {
report = new Report();
socket.on('dataChange', function(newData) {
report.update(newData);
});
});
function Report () {
this.update = function (data) {
socket.emit('updateReport', { data: data });
}
}
Error
Node gives me the following error.
socket.emit('updateReport', { data: data });
^ReferenceError: socket is not defined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将
socket
传递给Report
,如下所示:这样,
socket
就可以在Report
中访问。但是,您使用的
report
作为连接处理程序非本地的变量。您确定没有跨连接覆盖报告
吗?看来您更希望每个连接都有一个报告。在这种情况下,请将var
添加到report
赋值之前。You could pass
socket
toReport
like this:That way,
socket
is accessible inReport
.However, you used
report
as a variable that's not local to the connection handler. Are you sure you're not overwritingreport
across connections? It seems you rather want a report per connection. In that case, prependvar
to thereport
assignment.