[英]Socket.io + node : TypeError: Object #<Namespace> has no method
I have a simple JavaScript class like that : 我有一个简单的JavaScript类,例如:
function MySIOClass(io) { this.io = io this.ns = this.io.of('/notif') this.init() } MySIOClass.prototype.init = function (){ this.ns.on('connection', this.newClient) } MySIOClass.prototype.newClient = function (socket) { socket.on('msg', function (data){ this.handle_msg(data)})
}
}
MySIOClass.prototype.handle_msg = function (data) { // handle my message }
I get stuck on the function newClient , each time a socket.io client send an event 'msg', the console triggers 我陷入函数newClient ,每次socket.io客户端发送事件“ msg”时,控制台都会触发
TypeError: Object #
<Socket>
has no method 'handle_msg'TypeError:对象#
<Socket>
没有方法'handle_msg'
I tried to keep a reference of the operator this inside the function newClient like that : 我试图像这样在newClient函数中保留对运算符的引用:
MySIOClass.prototype.newClient = function (socket) { var c = this; socket.on('msg', function (data){ c.handle_msg(data)})
}
}
But no luck too, i got the following error about namespace : 但是也没有运气,我遇到了有关命名空间的以下错误:
TypeError: Object #
<Namespace>
has no method 'handle_msg'TypeError:对象#
<Namespace>
没有方法'handle_msg'
My class is exported via a module, everything works except when i try to add a listener with the on method of socket.io inside a class. 我的类是通过模块导出的,除了我尝试在类内使用socket.io的on方法添加侦听器时,其他所有方法都可以正常工作。 I have correctly used the "new" operator when i instantiated my class.
实例化类时,我已经正确使用了“ new”运算符。
Could you help me figure out what's happening ? 你能帮我弄清楚发生了什么吗? i tried several things, but none of them worked.
我尝试了几件事,但没有一个奏效。
Thanks for your time. 谢谢你的时间。
When you pass this.newClient
to .on('connection', ...)
, you are passing just the function itself and losing the ( this
) context. 当您将
this.newClient
传递给.on('connection', ...)
,您仅传递了函数本身,并且丢失了( this
)上下文。 You need to either create a wrapper function that can access the correct context to call newClient()
properly or create a bound version of newClient
. 您需要创建一个可以访问正确上下文以正确调用
newClient()
的包装器函数,或者创建newClient
的绑定版本。
First option: 第一种选择:
MySIOClass.prototype.init = function (){
var self = this;
this.ns.on('connection', function(socket) {
self.newClient(socket);
});
}
Second option: 第二种选择:
MySIOClass.prototype.init = function (){
this.ns.on('connection', this.newClient.bind(this));
}
Regarding the error inside newClient()
itself, you are correct in that you have to use a "self"/"that" variable that you can use to access the correct context to call handle_msg()
. 关于
newClient()
自身内部的错误,您必须使用“ self” /“ that”变量来访问正确的上下文,以调用handle_msg()
这是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.