Просмотр исходного кода

Commit 10-3: Created a form to submit comments.

Frederic G. MARAND 9 лет назад
Родитель
Сommit
e8cad5e698

+ 12 - 0
client/templates/comments/comment_submit.html

@@ -0,0 +1,12 @@
+<template name="commentSubmit">
+  <form name="comment" class="comment-form form">
+    <div class="form-group {{errorClass 'body'}}">
+      <div class="controls">
+        <label for="body">Comment on this post</label>
+        <textarea name="body" id="body" class="form-control" rows="3"></textarea>
+        <span class="help-block">{{errorMessage 'body'}}</span>
+      </div>
+    </div>
+    <button type="submit" class="btn btn-primary">Add comment</button>
+  </form>
+</template>

+ 48 - 0
client/templates/comments/comment_submit.js

@@ -0,0 +1,48 @@
+/**
+ * @file
+ *
+ *
+ * User: marand
+ * Date: 06/09/15
+ * Time: 22:05
+ */
+
+Template.commentSubmit.onCreated(function () {
+  Session.set('commentSubmitErrors', {});
+});
+
+Template.commentSubmit.helpers({
+  errorMessage: function (field) {
+    return Session.get('commentSubmitErrors')[field];
+  },
+  errorClass: function (field) {
+    return !!Session.get('commentSubmitErrors')[field] ? 'has-error' : '';
+  },
+});
+
+Template.commentSubmit.events({
+  'submit form': function (e, template) {
+    e.preventDefault();
+
+    var $body = $(e.target).find('[name=body]');
+    var comment = {
+      body: $body.val(),
+      postId: template.data._id
+    };
+
+    var errors = {};
+    if (!comment.body) {
+      errors.body =  'Please write some content';
+      return Session.set('commentSubmitErrors', errors);
+    }
+
+    Meteor.call('commentInsert', comment, function (error, commentId) {
+      if (error) {
+        throwError(error.reason);
+      }
+      else {
+        $body.val('');
+      }
+    });
+  }
+});

+ 5 - 0
client/templates/posts/post_page.html

@@ -6,5 +6,10 @@
         {{> commentItem}}
       {{/each}}
     </ul>
+    {{#if currentUser}}
+      {{> commentSubmit}}
+    {{else}}
+      <p>Please log in to leave a comment.</p>
+    {{/if}}
   </div>
 </template>

+ 21 - 0
lib/collections/comments.js

@@ -8,3 +8,24 @@
  */
 
 Comments = new Mongo.Collection('comments');
+
+Meteor.methods({
+  commentInsert: function (commentAttributes) {
+    check(this.userId, String);
+    check(commentAttributes, {
+      postId: String,
+      body: String
+    });
+    var user = Meteor.user();
+    var post = Posts.findOne(commentAttributes.postId);
+    if (!post) {
+      throw new Meteor.Error('invalid-comment', 'You must comment on a post');
+    }
+    var comment = _.extend(commentAttributes, {
+      userId: user._id,
+      author: user.username,
+      submitted: new Date()
+    });
+    return Comments.insert(comment);
+  }
+});