Получите this._id экземпляра коллекции в template.foo.rendered

Я пытаюсь включить модуль рейтинга из Semantic UI (http://semantic-ui.com/modules/rating.html) под статьями, чтобы пользователи могли оценивать их. Если пользователь оценивает статью, идентификатор статьи сохраняется в Meteor.user().profile.ratedItems.

Если пользователь переходит от статьи к другой, а затем возвращается к первой, модуль рейтинга должен отображаться как доступный только для чтения (чтобы пользователь не мог снова оценить ту же статью).

Проблема в том, что я не знаю, как проверить, хранится ли статья _id в Meteor.user().profile.ratedItems в template.foo.rendered, потому что this._id дает не идентификатор статьи, а идентификатор шаблона.

В template.foo.events и template.foo.helpers я могу проверить это с помощью предложения _.contains(Meteor.user().profile.ratedItems,this._id), и оно работает нормально везде, но не в шаблоне. foo.рендеринг. Теперь, даже если пользователь оценивает статью более одного раза, рейтинг в БД не меняется. Но мне нужно решить "визуальную" проблему.

Итак, вот код:

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, но пока не нашел никакого решения. Спасибо за помощь заранее.


person Alex Alexeev    schedule 15.01.2015    source источник


Ответы (1)


Вместо this вы можете использовать Template.currentData внутри обратного вызова rendered.

См. документы по адресу http://docs.meteor.com/#/full/template_currentdata. .

person stubailo    schedule 16.01.2015
comment
благодарю вас. Я попробую и приму ответ, если это сработает для меня. - person Alex Alexeev; 16.01.2015
comment
Просто изменил this._id в Template.foo.rendered на Template.currentData()._id, и все отлично сработало. Спасибо. - person Alex Alexeev; 16.01.2015