向上和向下按钮

时间:2016-02-04 19:22:03

标签: javascript meteor vote-up-buttons

我尝试实现向上或向下投票按钮,用户只需投票1次,1次投票。如果你已经投了一些东西,应该可以通过点击upvote按钮删除它,但我不知道缺少什么。我的代码如下所示。我想我必须实现一些真实的虚假陈述,但我尝试了一些事情,没有任何效果。我很感激你的帮助!

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()}});
            }
          }
  }});

2 个答案:

答案 0 :(得分:3)

您的一般方法是正确的,但您根本不需要Session变量,甚至不需要第一个单击处理程序。而且你不需要从函数中返回任何东西。

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() }
        }); 
      }
    }
  }
});

答案 1 :(得分:3)

你可以通过检查upvotes和downvotes中是否存在用户并相应地递增/递减来开始简单,然后将用户添加到集合中。

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.
    });
  }
});