0

私は、ユーザーが 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()}});
            }
          }
  }});
4

2 に答える 2

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() }
        }); 
      }
    }
  }
});
于 2016-02-04T19:46:57.327 に答える