使用Meteor会话切换模板 [英] Using Meteor sessions to toggle templates
问题描述
我是JavaScript和Meteor的新手,并且我试图为列表项创建编辑功能以便能够修改列表项的属性(来自Mongo文档)。如果我将editMode设置为项本身的布尔属性,我可以使它工作,但我希望它是本地的和临时的,而不是与文档本身一起存储。
I'm brand new to JavaScript and Meteor, and am a little stuck in trying to create edit functionality for a list item to be able to modify properties of the list item (from a Mongo document). I can make it work if I make editMode a boolean property of the item itself, but I'd like it to be local and temporary rather than stored with the document itself.
看看下面的代码,你会发现我还是绿色的,还没有完全理解我在做什么,但你应该能够理解我正在尝试做什么:)
Looking at the code below, you'll notice I'm still green and don't yet completely understand what I'm doing, but you should be able to understand what I'm trying to do :)
代码有点存在,但我试图根据切换编辑按钮来连接会话中的更改,以获取要渲染的编辑模式模板。这就是我所拥有的(剥离相关的东西):
The code is somewhat there, but am trying to hook up changes in the session, based on toggling an edit button, to get the edit mode template to render. Here's what I have (stripped down to the relevant stuff):
// Item template
<template name="item">
<div class="item">
<span>{{itemText}}</span>
<span class="glyphicon glyphicon-pencil item-edit" aria-hidden="true"></span>
</div>
<div class="mod-table">
{{#if this.editMode}}
{{> modTable}}
{{/if}}
</div>
</template>
// Associated .js file
Session.set(this.editMode, false);
Template.item.events({
'click .item-edit': function() {
if (this.editMode) {
Session.set(this.editMode, false);
} else {
Session.set(this.editMode, true);
}
}
});
推荐答案
不要使用会话
变量,因为它们是全局因此被视为不良做法,您应该使用与您的项目模板相关联的 ReactiveVar
。
Don't use Session
variables because they are global thus considered bad practice, you should use a ReactiveVar
tied to your item template instead.
item.html:
item.html :
<template name="item">
<div class="item">
<span>{{itemText}}</span>
<span class="glyphicon glyphicon-pencil item-edit" aria-hidden="true"></span>
</div>
<div class="mod-table">
{{#if editMode}}
{{> modTable}}
{{/if}}
</div>
</template>
item.js:
Template.item.created=function(){
this.editMode=new ReactiveVar(false);
};
Template.item.helpers({
editMode:function(){
return Template.instance().editMode.get();
}
});
Template.item.events({
'click .item-edit': function(event,template) {
var editMode=template.editMode.get();
template.editMode.set(!editMode);
}
});
别忘了 meteor add reactive-var
到你的项目!
这篇关于使用Meteor会话切换模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!