[英]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? 我如何在用户回答问题后使用新的
Math.random()
值重新运行查询以获得另一个随机问题?
If you replace Math.random()
with a reactive variable, that will cause your subscription to be reevaluated. 如果用反应性变量替换
Math.random()
,将导致重新评估您的订阅。 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: 在路由运行之前的某个位置(在文件顶部或在before挂钩中),初始化变量:
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. 请注意,您可能需要
question: Questions.findOne()
而不是question: Questions.find()
假设您的模板需要一个文档而不是一个游标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.