У меня есть upvotes и downvotes в моем приложении meteor, но пользователь может повышать и понижать так, как они хотят. Я пытаюсь сделать так, чтобы они могли делать только одно, а если они делают другое, оно удаляет предыдущее.Метеор. Пользователь может только увеличивать или уменьшать только один раз
Мои Автоформа выглядит как следует:
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 и наоборот
EDIT
Я установил его с помощью $ .inArray вместо _.contains
if ($.inArray(articles.upVoters, this.userId)) {