[英]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.