我在我的流星应用程序上运行了upvotes和downvotes但是用户可以根据需要进行upvote和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>
使用此代码,用户可以upvote并将其名称添加到upVoter,反之亦然
修改
我使用$ .inArray而不是_.contains
来修复它if ($.inArray(articles.upVoters, this.userId)) {
答案 0 :(得分:0)
我已经使用$ .inArray而不是_.contains修复了它。