获取 template.foo.rendered 中集合实例this._id



我尝试在文章下包含语义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,但还没有找到任何解决方案。提前感谢您的帮助。

代替 this ,您可以在rendered回调中使用Template.currentData

请参阅 http://docs.meteor.com/#/full/template_currentdata 中的文档。

最新更新