[英]Load template if checkbox is checked in Meteor
I'm playing around with Meteor and want to do something simple. 我正在玩流星,想做些简单的事情。 If a checkbox is checked, load a template.
如果选中此复选框,请加载模板。 So I've got:
所以我有:
<body>
<label>
<input type="checkbox" id="checker">
Load Text
</label>
{{> check}}
</body>
<template name="check">
{{#if isTrue}}
<h3>Some Text</h3>
{{/if}}
</template>
I'm thinking I would need a Session to keep state. 我在想我需要一个Session来保持状态。 So I wrote:
所以我写道:
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);
}
});
I think I'm confused how Sessions work in Meteor. 我想我对Sessions在Meteor中的工作方式感到困惑。 Any hints or help are appreciated.
任何提示或帮助,不胜感激。 Thanks.
谢谢。
You will need to bind your event to a parent template in this case; 在这种情况下,您需要将事件绑定到父模板。 eg:
例如:
<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>
And the js: 和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);
}
});
Normally, for loading dynamically the template, we will have the exact thing like that: dynamic template
通常,对于动态加载模板,我们将具有如下确切的信息:
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>
And in the parent js file 并在父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');});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.