javascript - 如果在 Meteor 中选中复选框则加载模板

标签 javascript meteor

我正在玩 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);
  }
});

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

最佳答案

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

<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);
    }
});

关于javascript - 如果在 Meteor 中选中复选框则加载模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34419384/

相关文章:

javascript - 我可以使用原始堆栈和堆栈帧重新创建错误对象吗?

javascript - 如何在javascript中创建cookie并在mvc3的 Controller 中使用

javascript - Jquery 切换模板表单

javascript - 如何在我的 angularjs 指令中切换 contenteditable 等属性的值?

javascript - 如何实现这个定价计算器

javascript - 有条件地加载 polyfill

mongodb - Meteor 无法连接到 MongoDB

javascript - 通过 id 匹配集合项

javascript - 在哪里可以使用 Meteor http 将 POST 数据传递到 api?

javascript - 在常规 JS 文件中使用 Meteor Iron Router 数据上下文?