【问题标题】:Load template if checkbox is checked in Meteor如果在 Meteor 中选中复选框,则加载模板
【发布时间】:2015-12-23 11:17:23
【问题描述】:

我正在玩 Meteor,想做一些简单的事情。如果选中复选框,则加载模板。所以我有:

<body>
  <label>
    <input type="checkbox" id="checker">
    Load Text
  </label>
  {{> check}}
</body>

<template name="check">
  {{#if isTrue}}
    <h3>Some Text</h3>
  {{/if}}
</template>

我想我需要一个 Session 来保持状态。于是我写了:

Session.setDefault('key', false);
Template.check.isTrue = function() { Session.get('key'); };
Template.check.events({
  'change #checker': function() {
    if (document.getElementById('#checker').checked)
      Session.set('key', true);
    else
      Session.set('key', false);
  }
});

我想我对 Sessions 在 Meteor 中的工作方式感到困惑。任何提示或帮助表示赞赏。谢谢。

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    在这种情况下,您需要将事件绑定到父模板;例如:

    <body>
      {{> parentTemplate}}
    </body>
    
    <template name="parentTemplate">
      <label>
        <input type="checkbox" id="checker">
        Load Text
      </label>
      {{> check}}
    </template>
    
    <template name="check">
      {{#if isTrue}}
        <h3>Some Text</h3>
      {{/if}}
    </template>
    

    还有js:

    Session.setDefault('key', false);
    
    // Edit: It appears that this is deprecated
    // Template.check.isTrue = function() { Session.get('key'); };
    
    // Use 'helpers' instead
    Template.check.helpers({
      'isTrue': function () {
        return Session.get('key');
      }
    })
    
    Template.parentTemplate.events({
      'change #checker': function() {
        // Also, no need for the pound sign here
        if (document.getElementById('checker').checked)
          Session.set('key', true);
        else
          Session.set('key', false);
        }
    });
    

    【讨论】:

    • 谢谢。这可能是我遗漏的东西,但我无法让您的代码正常工作。
    • 更新了答案(需要在帮助程序中返回,并且不推荐使用“Template.check.isTrue = ...”)。
    • 太棒了。我曾在某处看到语法很旧,但认为它仍然有效。将它放在父模板中似乎是我缺少的关键部分。
    • 看来我也可以选择不使用父模板的想法并使用'Template.body.events({...})。
    【解决方案2】:

    通常,为了动态加载模板,我们将得到类似的内容:dynamic template

    <body>
      <label>
        <input type="checkbox" id="checker">
        Load Text
      </label>
      {{>Template.dynamic template=getTemplate}}
    </body>
    
    <template name="check">
        <h3>Some Text</h3>
    </template>
    

    并且在父js文件中

    Template.parentTemplate.events({
      'change #checker': function(event) {
        if ($(event.target).attr('checked')) {
          Session.set('template', 'check');
        } else {
          Session.set('template', '');
        }
    });
    
    
    Template.parentTemplate.helper({
        getTemplate: function(){return Session.get('template');});
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      相关资源
      最近更新 更多