Nodragem Posted January 18, 2018 Share Posted January 18, 2018 Hello everybody, I am struggling with integrating socket.io in a oriented-object paradigm. One common problem with javascript and OOP are the callbacks and `this`. For instance, if you try to do something like: GameServer.prototype = { constructor : GameServer, onConnection : function(socket){ socket.on('new_player', this.onNewPlayer); }, onNewPlayer : function (data) { ... } } The bad news is that: in `onNewPlayer(data)` , `this` will NOT refer to `GameServer`. Instead, `this` will be referring to `socket`. One solution is: GameServer.prototype = { constructor : GameServer, onConnection : function(socket){ socket.on('new_player', (data) => this.onNewPlayer(data)); }, onNewPlayer : function (data) { ... } } The good news is that: in `onNewPlayer(data)` , `this` will refer to `GameServer`. The bad news is that: in `onNewPlayer(data)`, `this` does not refer to `socket` anymore. That facilitates OOP, but that prevents an easy use of `socket.emit()` for instance. Thus, what would be the easiest/prettiest way to get a reference to `socket` in `onNewPlayer(data)` and keep `this` referring to `GameServer`? Any suggestion is welcome Quote Link to comment Share on other sites More sharing options...
Arcanorum Posted January 18, 2018 Share Posted January 18, 2018 var _this; GameServer.prototype = { constructor : function(){ _this = this; }, onConnection : function(socket){ socket.on('new_player', _this.onNewPlayer(data)); } } I know it seems like a hack, but it is the cleanest solution that I use and lets me get stuff done easily. Nodragem 1 Quote Link to comment Share on other sites More sharing options...
Nodragem Posted January 18, 2018 Author Share Posted January 18, 2018 Thank you for your answer Arcanorum. If I understand well, with your solution, in `onNewPlayer(data)`, `this` will refer to `socket` while `_this` will refer to `GameServer`? The main problem I see with this solution is that you get `_this` in the global scope, so that if you define several classes, you would need to use `_this1`, `_this2`, etc... I will definitely keep your suggestion in mind, but I am happy to wait for other suggestions if there are ?? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.