![](/img/trans.png)
[英]in node.js / socket.io - which sockets, if any, are in a “room”?
[英]Node.js - socket.io - reference to io.sockets suddenly undefined
我有一个运行简单的socket.io服务的node.js服务器
当我引用this.io.sockets
以建立“连接”处理程序函数时,它工作正常。 但是,如果我以后引用this.io.sockets
,则会出现错误
TypeError: Cannot read property 'sockets' of undefined
我是node.js的新手,所以不确定在这里我做错了什么。
码:
var app = require('http').createServer();
var port = 8080;
app.listen(port);
function Serv() {
this.io = require('socket.io')(app)
this.addHandlers()
}
Serv.prototype.addHandlers = function () {
this.io.sockets.on("connection", function (socket) {
console.log('new connection');
socket.on('disconnect', function () {
console.log('disconnection');
if (this.io.sockets.adapter.rooms[phn] != null) { //Causes undefined error..
//do something
}
});
socket.on(SOCKETEVENTMESSAGE, function (data) {
if (this.io.sockets.adapter.rooms[phn] != null) { //Causes undefined error..
//do something
}
});
});
};
// Start the server
var serv = new Serv();
console.log('socket.io listening on ' + port);
如您所见,问题很明显
this.io.sockets.on("connection", function (socket) {
每当发生连接时,都会调用侦听器,因此作用域( this
)将有所不同。
您应该做的是,至少有三种方法,但我建议一种
将范围保存到变量并像这样由侦听器关闭
Serv.prototype.addHandlers = function () {
var _this = this;
this.io.sockets.on("connection", function (socket) {
console.log('new connection');
socket.on('disconnect', function () {
console.log('disconnection');
if (_this.io.sockets.adapter.rooms[phn] != null) {
//do something
}
});
问题是,每当您将函数声明为套接字事件的回调时,该函数都会被赋予其自己的作用域/上下文。 这意味着您失去了this
的价值。 默认情况下,在这种情况下, this
实际上指的是在其中运行了回调函数的任何上下文套接字。
JavaScript带有一种内置方式来确保使用所需的上下文: bind
Serv.prototype.addHandlers = function () {
this.io.sockets.on("connection", function (socket) {
console.log('new connection');
socket.on('disconnect', function () {
console.log('disconnection');
if (this.io.sockets.adapter.rooms[phn] != null) { 'this' has correct value
//do something
}
}.bind(this));
socket.on(SOCKETEVENTMESSAGE, function (data) {
if (this.io.sockets.adapter.rooms[phn] != null) { 'this' has correct value
//do something
}
}.bind(this));
}.bind(this));
};
为了避免陷入回调地狱 ,您可以分别声明函数,如下所示:
Serv.prototype.addHandlers = function () {
var onDisconnect = function () {
console.log('disconnection');
if (this.io.sockets.adapter.rooms[phn] != null) {
//do something
}
}.bind(this);
var handleEvent = function (data) {
if (this.io.sockets.adapter.rooms[phn] != null) {
//do something
}
}.bind(this);
function onConnect (socket) {
console.log('new connection');
socket.on('disconnect', onDisconnect);
socket.on(SOCKETEVENTMESSAGE, onHandleEvent);
}; // 'this' isn't required, so no binding necessary
this.io.sockets.on("connection", onConnect);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.