jeudi 12 février 2015

How do I re-run my Meteor publication to refresh the contents of a collection on the client?


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?





Aucun commentaire:

Enregistrer un commentaire