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

rad*_*von 1 javascript collections meteor

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

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

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

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

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
      };
  }
});
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*don 5

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

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

  Session.setDefault('randomValue', Math.random());
Run Code Online (Sandbox Code Playgroud)

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

  Meteor.subscribe('question', Session.get('randomValue'));
Run Code Online (Sandbox Code Playgroud)

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

  Session.set('randomValue', Math.random());
Run Code Online (Sandbox Code Playgroud)

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

  • 值得注意的是publish函数不必实际使用它的参数。您可能会在客户端上看到反应变量只是强制重新运行发布功能的一种手段。在内部,它可以计算另一个随机值,并确定客户应看到的问题。 (3认同)