我正在使用Meteor的聊天应用程序,我想制作它,所以你必须输入一些东西才能发送你的信息(这样你就可以输入很多次来让你的名字出现在聊天)。不幸的是我不知道怎么做,所以我希望这里有人可以提供帮助。以下是运行聊天应用的代码:
使用Javascript:
// render all of our messages in the ui
Template.chatBox.helpers({
"messages": function() {
return chatCollection.find();
}
});
// get the value for handlerbar helper user
Template.chatMessage.helpers({
"user": function() {
if(this.userId == 'me') {
return this.userId;
} else if(this.userId) {
getUsername(this.userId);
return Session.get('user-' + this.userId);
} else {
return 'anonymous-' + this.subscriptionId;
}
}
});
// when Send Chat clicked at the message to the collection
Template.chatBox.events({
"click #send": function() {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//Validation
var bot =Check_bots();
if(bot==false)
{
//add the message to the stream
chatStream.emit('chat', message);
}
else
{
}
},
"keypress #chat-message": function(e) {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
if (e.which == 13) {
//Validation
var bot =Check_bots();
if(bot==false)
{
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
console.log("you pressed enter");
e.preventDefault();
//repeat function from #send click event here
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
else
{
}
}
}
});
chatStream.on('chat', function(message) {
chatCollection.insert({
userId: this.userId,
subscriptionId: this.subscriptionId,
message: message
});
});
答案 0 :(得分:1)
这不是一个Meteor
特定的问题,而是一个简单的JavaScript
问题。您需要做的就是检查消息的length
:
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
var message = $('#chat-message').val();
// check to see if the message has any characters in it
if (!message.length) {
alert("You must enter a valid message!");
return;
}
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
您还可以使用!message.length
替换message.length > 3
来检查一定数量的字符。