开始使用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?", "")
});
我已经使用now.js正常工作的node.js服务器。
我正在尝试扩展聊天,以便当用户输入其名称时,会向服务器发送一条消息,指出“现在已加入聊天”。示例代码提示用户输入名称,并将其设置为now对象的名称。
now.name = prompt("What's your name?", "");
此时,now对象可用。因此,我不是简单地设置now.name,而是尝试设置now.name并通过调用distributeMessage发送消息('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报告错误消息
对象#&lt;对象&gt;没有方法'distributeMessage'。
我不明白为什么。可以设置now.name属性。控制台日志使用get distributeMessage显示对象并设置distributeMessage函数。当我点击'send-button'元素时,我可以发送消息。但是,此时我无法调用distributeMessage。
当我尝试调用方法时,now对象是否未完全加载?我是否需要包含某种'now'onLoadReady方法?为了在提示符后触发now.distributeMessage方法,我需要做什么?
答案 0 :(得分:1)
我找到了解决问题的方法。我需要用一个
包围调用来分发消息now.ready(function() {
now.distributeMessage(now.name + " has joined chat.");
})
似乎客户端现在名称空间可用,但现在所有服务器端调用仍需要javascript来完成处理。