【发布时间】:2015-03-14 11:32:47
【问题描述】:
我尝试在文章下包含来自语义 UI (http://semantic-ui.com/modules/rating.html) 的评级模块,以便用户能够对它们进行评级。如果用户对文章进行评分,文章 ID 将存储在 Meteor.user().profile.ratedItems 中。
如果用户从文章移到另一篇文章,然后又回到第一篇文章,评分模块应呈现为只读(因此用户无法再次评分同一篇文章)。
问题是我不知道如何检查文章 _id 是否存储在 template.foo.rendered 的 Meteor.user().profile.ratedItems 中,因为 this._id 给出的不是文章 ID,而是模板的 ID。
在 template.foo.events 和 template.foo.helpers 中,我可以通过句子 _.contains(Meteor.user().profile.ratedItems,this._id) 来检查它,它在任何地方都可以正常工作,但原因不是在 template.foo.rendered 中。现在,即使用户对一篇文章的评分超过一次,db 中的评分也不会改变。但我需要解决“视觉”问题。
代码如下:
JS:
Template.foo.helpers({
rate: function () {
return Math.floor(this.rating);
},
state : function () {
if (Meteor.userId()) {
if (_.contains(Meteor.user().profile.ratedItems,this._id)) {
return "rated"
} else {return "unrated"}
} else {
return ""
}
},
statetext: function () {
if (Meteor.userId()) {
if (_.contains(Meteor.user().profile.ratedItems,this._id)) {
return "Overall rating:" }
else { return "Rate the article:"}
} else {
return "Overall rating:"
}
}
});
Template.foo.rendered = function() {
if (Meteor.userId()) {
if (_.contains(Meteor.user().profile.ratedItems,this._id)) {
$('.ui.rating').rating('disable');
} else {
$('.ui.rating').rating();
}
} else {
$('.ui.rating').rating('disable');
}
};
Template.foo.events({
'click .unrated': function () {
var addedRating = $('.unrated').rating('get rating');
var currentArticleId = this._id;
var newsum = this.rating_sum+addedRating;
var newcount = this.rating_count+1;
var newrating = newsum/newcount;
Schools.update(currentSchoolId,{$inc: {rating_count:1}});
Schools.update(currentSchoolId,{$inc: {rating_sum:addedRating}});
Schools.update(currentSchoolId,{$set: {rating:newrating}});
Meteor.users.update({_id:Meteor.userId()},{$push: {'profile.ratedItems':currentArticleId}});
$('.ui.rating').rating({"set rating":Math.floor(newrating)});
$('.ui.rating').rating('disable');
}
});
HTML:
<template name="schoolPage">
<div class="ui center aligned blue segment">
{{#if currentUser}}{{statetext}}{{else}}Overall rating:{{/if}}
<div class="ui tiny heart rating {{state}}" data-rating="{{rate}}" data-max-rating="5"></div>
</div>
</template>
我考虑过使用 Session.set 和 Session.get 但还没有找到任何解决方案。 提前感谢您的帮助。
【问题讨论】:
标签: javascript mongodb templates meteor semantic-ui