chat_page.js 1.3 KB

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