I am currently developing a chat application using Meteor and I am facing an issue where I want to require users to type something before sending a message (to prevent spamming by hitting enter multiple times). Unfortunately, I am unsure of how to achieve this and I am hoping that someone here can provide assistance. Below is the code snippet for the chat application:
Javascript:
// displaying all messages in the UI
Template.chatBox.helpers({
"messages": function() {
return chatCollection.find();
}
});
// retrieving user value for handlerbar helper
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 button clicked, add message to 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 functionality 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
});
});