Sean L
Sean L

Reputation: 827

Meteor helper adds appropriate css for a brief second and then disappears

I am attempting to show a certain class if a user clicked the right answer or wrong answer through the {{checkAnswer}} helper below:

    <div class="question" {{attributes}}>
      <a href="#" data-value=0 class="checkOne upvote btn {{checkAnswer}}">A</a>
      {{answerOne}}
    </div>

A user submits an answer which creates a submission, and then ultimately that user submission is checked to see if it is correct. If the user submission is correct it should display btn-success, incorrect should be btn-danger, and else should be btn-primary.

Template.questionItem.helpers({   
checkAnswer: function() {
        var user = Meteor.user();
        var game = GameCollection.findOne({current: true});
        var currentQuestion = game.currentQuestion;
        var question = game.gameQuestions[currentQuestion];
        var correctAnswer = question.correctAnswer;
        var submission = Submissions.findOne({userId: user._id,
                                              gameId: game && game._id,
                                              currentQuestion: currentQuestion});
        if (submission && submission.submission === correctAnswer) {
            return 'btn-success';

        } else if (submission) {
            return 'btn-danger';
        } else {
            return 'btn-primary upvotable'
        }
    },

When I click a correct submission it turns green from btn-success for a fraction of a second (and if incorrect it turns red for a fraction of a second) but then ultimately goes to btn primary. Why does it not stay btn-success (or btn-danger)?

Upvotes: 0

Views: 64

Answers (1)

strack
strack

Reputation: 574

Something in the context is changing. Meteor data contexts are built in such a way that all the 'current' checking you're doing isn't necessary. You can instead access the current data context using this, which will significantly simplify your code.

I'd start by checking if the submission is correct or not on the server side, and then storing that as a property of the submission itself. Then, you can do a simple if...then to return the correct bootstrap class name.

Here's a simple example: meteorpad

And if you want the JS files to quickly put into a brand new project, here's a Gist.

You'll notice in both of those how you can use this._id or this.correct to access the correct/current data context. Hope that helps / gets you on the right track.

Upvotes: 1

Related Questions