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

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.