“赞成”和“反对”按钮

Up and Downvote button

本文关键字:按钮 反对 赞成      更新时间:2023-09-26

>我尝试实现一个赞成或反对的按钮,用户只能投票 1 次赞成和 1 次反对。如果您已经对某些内容投了赞成票,那么应该可以通过再次单击点赞按钮将其删除,但我不知道这缺少什么。我的代码如下所示。我想我必须用虚假陈述的真实来实现一些东西,但我尝试了一些事情,但没有任何效果。我将不胜感激你的帮助!

Template.postArgument.events({
 'click':function() {
  Session.set('selected_argument', this._id);
  },
 'click .yes':function() {
          if(Meteor.user()) {
            var postId = Arguments.findOne({_id:this._id})
            console.log(postId);
            if($.inArray(Meteor.userId(), postId.votedUp) !==-1) {
              return "Voted";
            } else {
        var argumentId = Session.get('selected_argument');
        Arguments.update(argumentId, {$inc: {'score': 1 }}); 
        Arguments.update(argumentId, {$addToSet: {votedUp: Meteor.userId()}});
            }
          }
  }});

您的一般方法是正确的,但是您根本不需要会话变量,甚至不需要第一次单击处理程序。而且您根本不需要从函数中返回任何内容。

Template.postArgument.events({
  'click .yes': function(){
    if ( Meteor.user() ) {
      var post = Arguments.findOne({_id:this._id});
      if ( $.inArray(Meteor.userId(), post.votedUp) === -1 ) {
        Arguments.update(this._id, {
          $inc: { score: 1 },
          $addToSet: { votedUp: Meteor.userId() }
        }); 
      } else {
        Arguments.update(this._id, {
          $inc: { score: -1 },
          $pull: { votedUp: Meteor.userId() }
        }); 
      }
    }
  }
});

您可以通过检查用户在赞成票和反对票中的存在以及相应的递增/递减,然后将用户添加到集合中来开始。

Meteor.methods({
  'downvote post': function (postId) {
    check(postId, String);
    let post = Posts.findOne(postId);
    Posts.update(postId, post.downvoters.indexOf(this.userId !== -1) ? {
      $inc: { downvotes: -1 },               // remove this user's downvote.
      $pull: { downvoters: this.userId }     // remove this user from downvoters
    } : {
      $inc: { downvotes: 1 },                // add this user's downvote
      $addToSet: { downvoters: this.userId } // add this user to downvoters.
    });
  }
});