node.js - 使用now.js调用distributeMessage方法时出错

标签 node.js chat nowjs-sockets

开始使用 now.js 框架。我正在尝试使用 now.js 中的示例代码来实现聊天。为了完整性而包括在这里。

<script src="http://localhost:8080/nowjs/now.js" type="text/javascript"></script>

<!-- HTML for Chat Here  -->

$(document).ready(function() {

  now.receiveMessage = function(name, message) {
    $(".chattext").append("<br>" + name + ": " + message);
    $(".chattext").attr({ scrollTop: $(".chattext").attr("scrollHeight") });
  }

  $("#send-button").click(function() {
    now.distributeMessage($("#text-input").val());
    $("#text-input").val("");
  });

  now.name = prompt("What's your name?", "")

});

我的 Node.js 服务器和 now.js 工作正常。

我正在尝试扩展聊天功能,以便当用户输入其姓名时,系统会向服务器发送一条消息,指出“现已加入聊天”。示例代码提示用户输入名称并将其设置为 now 对象的名称。

now.name = prompt("What's your name?", "");

此时,now对象就可用了。因此,我不是简单地设置 now.name,而是尝试设置 now.name 并通过调用 allocateMessage('John 已加入聊天。') 发送消息。

var p = prompt("What's your name?", "");
if (!p) {
    // errs here
} else {
    now.name = p;
    now.distributeMessage(now.name + " has joined chat.");
}

Chrome 和 Firefox 报告错误,内容为

对象 # 没有方法“distributeMessage”。

我不明白为什么。可以设置 now.name 属性。控制台日志显示具有 get allocateMessage 和 set allocateMessage 函数的对象。当我单击“发送按钮”元素时,我可以发送消息。但是,我此时无法调用 allocateMessage。

当我尝试调用方法时,现在的对象是否未完全加载?我是否需要包含某种“现在”onLoadReady 方法?我需要做什么才能在提示后触发 now.distributeMessage 方法?

最佳答案

我找到了解决我的问题的方法。我需要用一个来包围分发消息的调用

now.ready(function() {
  now.distributeMessage(now.name + " has joined chat.");
})

看来客户端现在命名空间可用,但所有服务器端调用仍然需要 javascript 来完成处理。

关于node.js - 使用now.js调用distributeMessage方法时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8513430/