【问题标题】:How to pass variable argument in meteor find method如何在流星查找方法中传递变量参数
【发布时间】:2015-07-12 15:46:28
【问题描述】:

在使用“qnum”变量参数作为值进行查找查询时,它不会返回任何数据。是不是因为对象内部变量作用域的限制?

测验.js 文件

Questions = new Mongo.Collection("questions");

if (Meteor.isClient) {

  var qnum = 1;

  Template.question.events({

    "click #submit-btn": function (event, template) {
      //Increment question number when user click on submit button which loads the next question
      qnum += 1;
    }

  });


  Template.body.helpers({
    questions: function (qnum) {
      return Questions.find({qnum: qnum});
    }
  });
}

测验.html 文件

<div class="quiz">
    <div class="score-board">
        {{#each questions}}
            {{> question}}
        {{/each}}
    </div>
</div>
</body>

<template name="question">
    <div class="qa-wrapper" id="{{qnum}}">
        <div class="questions">{{title}}</div>
        <div class="options">
                {{#each options}}
                <input type="checkbox" name="{{this}}"/>{{this}} <br />
                {{/each}}
            <button id="submit-btn">Submit</button>
        </div>
    </div>
</template>

问题数据库集合

{ "_id" : ObjectId("55a207a21c4dbe14cf9837c7"), "qnum" : 1, "title" : "Question 1", "options" : [ "A", "B", "C", "D" ] }
{ "_id" : ObjectId("55a207b31c4dbe14cf9837c8"), "qnum" : 2, "title" : "Question 2", "options" : [ "A", "B", "C", "D" ] }

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    我的预感是,当您为模板帮助程序 questions(qnum) 设置参数时,它需要一个参数,但随后在 {{#each questions}} 位中您不会传递任何内容。尝试删除 template.helper def 中的qnum 使其变为

    Template.body.helpers({
      questions: function () {
        return Questions.find({qnum: qnum});
      }
    });
    

    未经测试。让我知道它是否有效。

    要真正让您的助手在单击按钮时重新运行,您需要使查询参数 (qnum) 具有响应性。在这里,Meteor 提供了多种选择,最明显的一种是将您的 qnum 值存储在 Session 中。

    Session.set("qnum", qnum)
    

    然后在模板助手查询中

    return Questions.find({qnum: Session.get("qnum") });
    

    【讨论】:

    • 谢谢,现在它返回对象。但是,我面临的另一个问题是,单击按钮时增加的值不会通过 Questions.find 方法返回。
    • 我更新了我的答案,请检查它是否适合你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2020-08-21
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多