Monday, 15 July 2013

javascript - How do I properly encapsulate a socket.io socket? -


This code is running in my node. JS server application:

  io.sockets . ('Connection', function (socket) {var c = new client (socket, tools. GenerateID); are waiting; Push (c); allClients.push (c); if (waitingClients.length == = 2) {ActiveGames.push (New game ([waitingClients.pop ()), pst ()]))))}}}); Function client (socket, id) {this.Socket = socket; This.ID = ID; this. Player = new player (); This.Update = function {socket.emit ('update', {actions: this.Player.Actions, buys: this.Player.Buys, Coins: this.Player.Coins, Hand: this.Player.Hand , Step: this.Player.Phase, Supply: Supply}}}} Socket.on ('play', function (data) {console.log (data); console.log (this.Player);}); Socket Emit ('id', id);}   

The part I am having trouble with is the event handler for the 'play' event. I console.log (this. Player) Output Undefined . I think why this is wrong, because 'this' is my client object (socket? Anonymous function?) Refers to the thing, but I do not know how to rearrange the code to handle play events properly, and there is full access to the members of the client object.

You just this inside client .

  function client (socket, id) {var self = this; ... socket.one ('play', function (data) {self.Player.play ();});    

No comments:

Post a Comment