【问题标题】:Node.js javascript modules on client side [closed]客户端的Node.js javascript模块[关闭]
【发布时间】:2013-04-07 15:52:52
【问题描述】:

我正在使用 node.js+express+socket.io 编写游戏。我花了很长时间才到达我现在的位置,但我觉得它终于找到了我。 我有以这种方式提供 html 和 js 文件的服务器:

app.post('/game', function(req, res) {
     handleGame(req, res); //it opens file using fs and forwards with res.end(readFile);
});

app.get('/scripts/*', function(req, res) {
     handleStatic(req, res); //same schema
});

现在,我已登录并在现场 game.html(从第一个 app.post 收到)。 它加载正常,initRight 更改为“bbbb”,如果我在 Firefox 中打开“源代码”,我可以单击并查看 player.jsgame.js 源代码。但是,在 game.js 模块的 init() 函数内部,应该将 initRight 字段再次更改为“AAAAA”,但正如我所见,玩家模块中的 Player 函数在游戏模块中是不可见的(我已经检测到当我在将 socket.io 处理程序移动到不同的模块)。我这样做是因为我在不同的项目中看到过它,我真的不希望下一次通过放置一些 require.js 来获得 require() 函数等而不知所措。我的问题是它应该工作吗?如果是,为什么它可能不在这里?

【问题讨论】:

  • 很难说出你在问什么。我建议您在此处显示与问题相关的代码。

标签: javascript node.js


【解决方案1】:

虽然您的问题令人困惑,并且我没有看到您的问题与 NodeJS 的联系,但问题是您的 JavaScript 存在多个问题。

我把你的代码复制到了 JSBin:

http://jsbin.com/iqudic/4/edit(直播:http://jsbin.com/iqudic/4

然后,我稍微清理了一下。

您可能希望将关联的属性放在 Player 对象的实例上,而不是像以前那样将它们作为新对象返回。

var Player = function(playerNick, playerId, playerSocket) {
  this.nick = playerNick;
  this.id = playerId;
  this.socket = playerSocket;
};

其次,这导致AAAAAA 不出现:

function init() {
    // socket and socket.id should be defined before creating the Player
    localPlayer = new Player('AAAAAA', socket.id, socket);
    document.getElementById('initRight').innerHTML = localPlayer.nick;
}

您的代码假定init 函数中有一个socket.idsocket 对象可用。它在那条线上崩溃了。您应该经常查看您最喜欢的网络浏览器的控制台窗口。

【讨论】:

  • 感谢 WiredPrairie,您的回复解决了我的两个问题;)
猜你喜欢
  • 1970-01-01
  • 2019-10-31
  • 2011-11-03
  • 2014-01-20
  • 2011-12-19
  • 1970-01-01
  • 2012-08-05
  • 2014-05-25
  • 2019-12-17
相关资源
最近更新 更多