I have a simple JavaScript class like that :
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
TypeError: Object #
<Socket>
has no method 'handle_msg'
I tried to keep a reference of the operator this inside the function newClient like that :
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'
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. I have correctly used the "new" operator when i instantiated my class.
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. 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
.
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()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.