2013-02-01 83 views
1

此問題涉及NodeJS中的WebSocket API(即var webSocketServer = require('websocket')。server;)。訪問Websocket.onmessage()外的變量

function Game(canvas) { 
    this.wArray; 
    this.runConnection(); 
    // I want to be able to see changes in variables at this point 
    console.log(this.wArray[1][2]); // is out of scope or something 
} 

_p = Game.prototype; 

_p.runConnection = function() { 
    this.connection = new WebSocket('ws://localhost:1337'); 
    this.connection.onmessage = function (message) { 
      this.wArray = JSON.parse(message.data); 
    }; 
    // code here runs before code inside onmessage, it must be asychronous 
}; 

所以我當我從服務器接收郵件時,我應該能夠採取的消息,並更新我的代碼一些變量和這樣的。目前,我所能做的只是更新onmessage函數內部的東西。在線的所有示例僅顯示在onmessage中使用console.log()的人員。我希望服務器能夠發送我的客戶信息,然後使用該信息更新遊戲運行過程中的某些方面。我認爲onmessage()存在一定程度的異步性。

請告訴我如何將通過WebSocket.onmessage()傳遞給我的數據存儲到可以在整個遊戲中訪問的變量中。

回答

0

我會建議看看now.js,它允許客戶端和服務器在相同的命名空間中操作,這樣可以讓兩端共享東西。

編輯..

我還在研究這個,顯然事情正在發生。此線程解釋它link

0

onMessage作爲回調函數異步觸發。因此,您必須注意您正在使用的變量範圍。有許多可能的使用:代理,修改範圍,功能,bind()等,您可以搜索以前的答案。 (有很多)

作爲一個簡單的例子,你可能會使用一個自變量在其他地方訪問它;然而,它顯然取決於整個腳本的目的。

function Game(canvas) { 
    this.wArray = []; 
    this.runConnection(); 
    console.log(this.wArray[1][2]); 
    //log() will likely not work as you should wait for [1][2] to be filled 
} 

_p = new Game(); 

_p.runConnection = function() { 
    this.connection = new WebSocket('ws://localhost:1337'); 
    var self = this; 
    this.connection.onmessage = function (message) { 
      self.wArray.push(JSON.parse(message.data)); 
     }; 
};