[英]How do I hide dynamic elements in Meteor?
因此,我有一堆模板,将使用{{#each game}}
进行迭代,显示以下模板:
<template name="game">
{{#if condition}}
<div class="box">
Page 1
</div>
{{else}}
<div class="box">
Page 2
</div>
{{/if}}
</template>
我想在单击“页面1”框时显示“页面2”,所以我有以下内容:
Template.game.events({
'click .box': function(e) {
Session.set("condition", true);
}
});
但是,我不希望所有其他游戏模板都过渡到第2页,而只需单击一下即可。 我该如何完成?
编辑:更改应只影响当前用户,而不是所有用户。
假设您的游戏存储在Meteor.Collection
,而condition
是文档中的一个属性,应反映所有用户(不仅是当前用户),因此您可以执行以下操作:
Template.game.events({
'click .box': function(event, template) {
Games.update(
{_id: template.data._id},
{$set: {condition: !template.data.condition}}
);
}
});
如果只影响当前用户,则可以使用特定于模板实例的会话变量,并使用名为condition
的帮助器函数将其返回:
Template.game.events({
'click .box': function(event, template) {
Session.set("condition-" + template.data._id, true);
}
});
Template.game.condition = function() {
return Session.get("condition-" + this._id);
};
您可以使用本地集合实现类似的功能。
不要使用会话变量! 究其原因,就是您遇到了问题,它们等同于旧的全局变量。 而是使用模板的数据,它是本地的,在这种情况下可以用来控制所需的行为。
对于您示例中的模板:
Template.game.created = function() {
this.data.conditionValue = 'something';
this.data.conditionDep = new Deps.Dependency();
};
Template.game.condition = function() {
this.conditionDep.depend();
return this.conditionValue;
};
Template.game.events({
'click .box': function(e, t) {
t.data.conditionValue = 'somethingElse';
t.data.conditionDep.changed();
},
});
我还觉得使用id为id的会话听起来不是最好的主意,并发现此答案似乎比使用session更好: 使用Meteor会话切换模板
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.