我如何重新运行 我的 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()