簡體   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