Sign in to follow this  
Nodragem

Socket.io and Oriented Object Paradigm

Recommended Posts

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 :)

Share this post


Link to post
Share on other sites

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 :) ??

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.