javascriptmeteorvote-up-buttons

Up and Downvote button


I try to achieve an up or downvote button where a user is able to vote just 1 time up and 1 time down. If you already have upvoted something it should be possible to remove that with another click on the upvote button, but i dont know what is missing for this. My code looks like the following. I guess i have to implement something with a true of false statement but i tried some things and nothing worked. I would appreciate your help!

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

Solution

  • Your general approach is correct however you don't need the Session variable at all or even the first click handler. And you don't need to return anything at all from the function.

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