I'm creating a quiz app. I want to show a single random question, take the user's answer, show feedback, and move to another random question.
I'm using this to publish a single random question:
getRandomInt = function(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
};
randomizedQuestion = function(rand) {
// These variables ensure the initial path (greater or less than) is also randomized
var greater = {$gte: rand};
var less = {$lte: rand};
var randomBool = !!getRandomInt(0,1);
var randomQuestion = Questions.find({randomizer: randomBool ? greater : less }, {fields: {body: true, answers: true}, limit: 1, sort: {randomizer: 1}});
// If the first attempt to find a random question fails, we'll go the other direction.
if (randomQuestion.count()) {
return randomQuestion;
} else {
return Questions.find({randomizer: randomBool ? less : greater}, {fields: {body: true, answers: true}, limit: 1, sort: {randomizer: 1}});
}
};
Meteor.publish("question", function(rand) {
if (rand) {
return randomizedQuestion(rand);
}
});
I have a route that subscribes to that publication:
Router.route("/", {
name:"quiz",
template:"question",
subscriptions: function() {
this.questionSub = Meteor.subscribe("question", Math.random());
},
data: function() {
return {
question: Questions.find(),
ready: this.questionSub.ready
};
}
});
How can I re-run the query with a new value for Math.random()
in order to get another random question after the user answers the question?
If you replace Math.random()
with a reactive variable, that will cause your subscription to be reevaluated. For simplicity I'll use a session variable in this example.
Somewhere before the route runs (at the top of the file or in a before hook), initialize the variable:
Session.setDefault('randomValue', Math.random());
Then change your subscription to use it:
Meteor.subscribe('question', Session.get('randomValue'));
Finally, whenever you want to restart the subscription and update your data context, change the variable again:
Session.set('randomValue', Math.random());
Note you may want question: Questions.findOne()
instead of question: Questions.find()
assuming your template needs a document instead of a cursor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.