2013-03-26 62 views
0

此代碼是在我的Node.js服務器應用程序運行:如何正確封裝socket.io套接字?

io.sockets.on('connection', function (socket) { 

    var c = new Client(socket, Tools.GenerateID()); 

    waitingClients.push(c); 
    allClients.push(c); 

    if (waitingClients.length === 2) 
    { 
     activeGames.push(new Game([waitingClients.pop(), waitingClients.pop()])); 
    } 
}); 

function Client(socket, id) 
{ 
    this.Socket = socket; 
    this.ID = id; 
    this.Player = new Player(); 

    this.Update = function(supply) 
    { 
     socket.emit('update', { Actions: this.Player.Actions, Buys: this.Player.Buys, Coins: this.Player.Coins, Hand: this.Player.Hand, Phase: this.Player.Phase, Supply: supply}); 
    } 

    socket.on('play', function(data) { 
     console.log(data); 
     console.log(this.Player); 
    }); 

    socket.emit('id', id); 
} 

我遇到的麻煩的部分是在「玩」事件的事件處理程序。 console.log(this.Player)輸出undefined。我不明白爲什麼它是錯誤的,因爲'this'是指除了我的客戶端對象(套接字?匿名函數?)之外的東西,但我不知道如何重新安排代碼來正確處理'play'事件並且可以完全訪問Client對象的成員。

回答

1

您只需將this存儲在Client的其他變量中。

function Client(socket, id) 
{ 
    var self = this; 
    ... 

    socket.on('play', function(data) { 
     self.Player.play(); 
    }); 
+0

哦,我的天哪,我怎麼會忘記。我甚至看過一堆代碼示例。謝謝! – 2013-03-26 23:33:53