繁体   English   中英

如何重新运行Meteor发布以刷新客户端上集合的内容?

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

我正在创建一个测验应用程序。 我想显示一个随机问题,获取用户的答案,显示反馈,然后转到另一个随机问题。

我正在使用它发布一个随机问题:

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);
  }
});

我有一条订阅该出版物的路线:

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
      };
  }
});

我如何在用户回答问题后使用新的Math.random()值重新运行查询以获得另一个随机问题?

如果用反应性变量替换Math.random() ,将导致重新评估您的订阅。 为简单起见,在此示例中,我将使用会话变量。

在路由运行之前的某个位置(在文件顶部或在before挂钩中),初始化变量:

  Session.setDefault('randomValue', Math.random());

然后更改您的订阅以使用它:

  Meteor.subscribe('question', Session.get('randomValue'));

最后,每当您要重新启动订阅并更新数据上下文时,请再次更改变量:

  Session.set('randomValue', Math.random());

请注意,您可能需要question: Questions.findOne()而不是question: Questions.find()假设您的模板需要一个文档而不是一个游标。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM