此問題涉及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()傳遞給我的數據存儲到可以在整個遊戲中訪問的變量中。