Javascript Node.js-socket.io-未定义对io.sockets的引用
我有一个node.js服务器运行一个简单的socket.io服务 当我引用Javascript Node.js-socket.io-未定义对io.sockets的引用,javascript,node.js,socket.io,undefined,Javascript,Node.js,Socket.io,Undefined,我有一个node.js服务器运行一个简单的socket.io服务 当我引用this.io.sockets以建立“连接”处理程序函数时,它工作正常。但是如果我以后引用这个.io.sockets,我会得到一个错误 TypeError: Cannot read property 'sockets' of undefined 我是node.js的新手,所以不确定我在这里做错了什么 代码: 正如你所看到的,问题是显而易见的 this.io.sockets.on("connection", functio
this.io.sockets
以建立“连接”处理程序函数时,它工作正常。但是如果我以后引用这个.io.sockets
,我会得到一个错误
TypeError: Cannot read property 'sockets' of undefined
我是node.js的新手,所以不确定我在这里做错了什么
代码:
正如你所看到的,问题是显而易见的
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
}
});
问题在于,无论何时将函数声明为套接字事件的回调,函数都会被赋予自己的作用域/上下文。这意味着您将丢失此的值。默认情况下,在这种情况下,
这个
实际上是指运行回调函数的上下文套接字
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);
};
.
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);
};