2016-09-13 45 views
0

我在我的流星應用上工作upvotes和downvotes,但用戶能夠upvote和downvote儘可能多的,他們想要的。我試圖做到這一點,所以他們只能做一個,如果他們做了另一個它刪除以前。流星 - 用戶只能贊成或downvote一次

我AUTOFORM看起來如下:

ArticleSchema = new SimpleSchema({ 
    title: { 
    type: String, 
    label: "Article title", 
    autoform: { 
     placeholder: "full article title here" 
    } 
    }, 
    url:{ 
    type: String, 
    label: "URL", 
    autoform: { 
     placeholder: "http://website.com" 
    } 
    }, 
    username:{ 
    type: String, 
    label: "Author", 
    autoValue: function() { 
     return Meteor.user().username 
    } 
}, 
    author:{ 
    type: String, 
    label: "Author", 
    autoValue: function() { 
     return this.userId 
    }, 
    autoform: { 
    type: "hidden" 
    } 
}, 
    autoform: { 
    type: "hidden" 
    } 
    }, 
    createdAt: { 
    type: Date, 
    label: "Created At", 
    autoValue: function(){ 
     return new Date() 
    }, 
    autoform: { 
     type: "hidden" 
    } 
    }, 
    upvote: { 
    type:Number, 
    optional:true 
    }, 
    upVoters:{ 
    type:Array, 
    optional:true 
    }, 
    'upVoters.$':{ 
    type:String 
    }, 
    downvote: { 
    type:Number, 
    optional:true 
    }, 
    downVoters:{ 
    type:Array, 
    optional:true 
    }, 
    'downVoters.$':{ 
    type:String 
    }, 
}); 

我的活動:

Template.articleOutput.events({ 
    "click .upvote": function(){ 
    var articles = Articles.findOne({ _id: this._id }); 
    if(articles) { 
     if (_.contains(articles.downVoters, this.userId)) { 
     Articles.update({ 
      _id: this._id 
      }, 
      { 
      $pull: { 
       downVoters: this.userId 
      }, 
      $addToSet: { 
       upVoters: this.userId 
      }, 
      $inc: { 
       downvote: -1, 
       upvote: 1 
      } 
      } 
     ); 
     } 
     Articles.update(this._id, {$addToSet: {upVoters: Meteor.userId()}, $inc: {upvote: 1}}); 
    } 
    }, 

    "click .downvote": function(){ 
    var articles = Articles.findOne({ _id: this._id }); 
    if(articles) { 
     if (_.contains(articles.upVoters, this.userId)) { 
     Articles.update({ 
      _id: this._id 
      }, 
      { 
      $pull: { 
       upVoters: this.userId 
      }, 
      $addToSet: { 
       downVoters: this.userId 
      }, 
      $inc: { 
       downvote: 1, 
       upvote: -1 
      } 
      } 
     ); 
     } 
     Articles.update(this._id, {$addToSet: {downVoters: Meteor.userId()}, $inc: {downvote: 1}}); 
    } 
    } 
}); 

和HTML:

<template name="articleOutput"> 
    <div class="outputBoxHome" > 
     <div class="vote"> 
     <div class="upvote"> 

     </div> 
     <div class="downvote"> 

     </div> 
     </div> 
     <div class="outputBoxHomeContent"> 
     <a href="/articles/{{_id}}"><h4>{{title}}</h4></a> 
     </div> 
    </div> 
</template> 

有了這個代碼,用戶可以給予好評,它會被添加爲以及他們的名字upVoter,反之亦然

編輯

我用$ .inArray代替_.contains

if ($.inArray(articles.upVoters, this.userId)) { 

回答

0

我以代替_.contains $ .inArray固定它固定它。