chat_page.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. Template.chat_page.helpers({
  2. messages: function () {
  3. console.log("messages context", this);
  4. const chat = Chats.findOne({ _id: Session.get("chatId") });
  5. return chat.messages;
  6. },
  7. other_user: function () {
  8. return this;
  9. }
  10. });
  11. Template.chat_page.events({
  12. // this event fires when the user sends a message on the chat page
  13. "submit .js-send-chat": function (event) {
  14. // stop the form from triggering a page reload
  15. event.preventDefault();
  16. // see if we can find a chat object in the database
  17. // to which we'll add the message
  18. const chat = Chats.findOne({_id: Session.get("chatId")});
  19. if (chat) {// ok - we have a chat to use
  20. let msgs = chat.messages; // pull the messages property
  21. if (!msgs) {// no messages yet, create a new array
  22. msgs = [];
  23. }
  24. // is a good idea to insert data straight from the form
  25. // (i.e. the user) into the database?? certainly not.
  26. // push adds the message to the end of the array
  27. msgs.push({ text: event.target.chat.value });
  28. // reset the form
  29. event.target.chat.value = "";
  30. // put the messages array onto the chat object
  31. chat.messages = msgs;
  32. // update the chat object in the database.
  33. Chats.update(chat._id, chat);
  34. }
  35. }
  36. });