我尝试将语义UI(http://semantic-ui.com/modules/rating.html)中的评分模块包含在用户可以对其进行评分的文章下。如果用户对文章进行评分,则文章ID将存储在Meteor.user()。profile.ratedItems中。
如果用户离开该文章转到另一篇文章,然后又回到第一篇文章,则评级模块应呈现为只读(因此,用户无法再次对同一篇文章进行评级)。
问题是我不知道如何检查template_foo.rendered中的文章_id是否存储在Meteor.user()。profile.ratedItems中,因为this._id不是提供文章ID,而是提供模板ID。
在template.foo.events和template.foo.helpers中,我可以通过句子_.contains(Meteor.user()。profile.ratedItems,this._id)进行检查,它在任何地方都可以正常运行,但原因不在模板中。 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,但是还没有任何解决方案。
预先感谢您的帮助。
最佳答案
可以在this
回调中使用Template.currentData
代替rendered
。
请参阅http://docs.meteor.com/#/full/template_currentdata上的文档。
关于javascript - 在template.foo.rendered中获取集合实例的this._id,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27974188/