1

开始使用 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 并通过调用 deployMessage('John has joined chat.') 发送消息

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

Chrome 和 firefox 报告错误,内容为

对象#<Object> 没有方法“distributeMessage”。

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

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

4

1 回答 1

1

我找到了解决我的问题的方法。我需要围绕呼叫分发消息

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

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

于 2011-12-15T18:12:02.743 回答