无论出于什么原因,我都无法用无数小时的疑难解答来解决这个问题。我有一些简单的帮助与一个启动3 nav-tabs列表。
我想呈现一个不同的模板,基于哪个列表项是活动的。以下是我的帮手:
Template.Profile.helpers({
'personal':function(){
if($('.profile-info').hasClass('active')) {
return true;
} else {
return false;
}
},
'groups':function(){
if($('.profile-groups').hasClass('active')) {
return true;
} else {
return false;
}
},
'commitments':function(){
if($('.profile-commitments').hasClass('active')) {
return true;
} else {
return false;
}
}
});这是我的HTML:
<ul class="nav nav-tabs">
<li class="active profile-info"><a href="#">Personal Info</a></li>
<li class="profile-groups"><a href="#">Groups</a></li>
<li class="profile-commitments"><a href="#">Commitments</a></li>
</ul>
{{#if personal}}
{{> ProfilePersonal}}
{{else}}
{{#if groups}}
{{> ProfileGroups}}
{{else}}
{{> ProfileCommits}}
{{/if}}
{{/if}}发布于 2015-12-08 11:09:30
当您单击一个选项卡时,将不会重新运行帮助程序,因为没有任何响应性数据更改来使计算无效。
更多的Meteor-ish方法是添加一个反应性变量,以保存制表符状态,并在事件侦听器中更改该状态。
<template name="Profile">
<ul class="nav nav-tabs">
{{#each tabs}}
<li class="{{isActive @index}} profile-{{name}}"><a href="#">{{title}}</a></li>
{{/each}}
</ul>
{{> Template.dynamic template=tpl}}
</template>@index引用当前循环的索引,并将其作为参数提供给isActive助手。
然后,您的JavaScript文件可以包含选项卡和处理代码的定义:
var tabs = [{
idx: 0,
name: "info",
title: "Personal Info",
template: "ProfilePersonal"
}, {
idx: 1,
name: "groups",
title: "Groups",
template: "ProfileGroups"
}, {
idx: 2,
name: "commitments",
title: "Commitments",
template: "ProfileCommits"
}];制表符是一个普通的JS数组。以下代码在模板的上下文中使用它们:
Template.Profile.helpers({
// get current sub-template name
tpl: function() {
var tpl = Template.instance();
return tabs[tpl.tabIdx.get()].template;
},
// get the tabs array
tabs: function() {
return tabs;
},
// compare the active tab index to the current index in the #each loop.
isActive: function(idx) {
var tpl = Template.instance();
return tpl.tabIdx.get() === idx ? "active" : "";
}
});
Template.Profile.events({
'click .nav-tabs > li': function(e, tpl) {
tpl.tabIdx.set(this.idx);
}
});
Template.Profile.onCreated(function() {
this.tabIdx = new ReactiveVar();
this.tabIdx.set(0);
});创建模板(onCreated())时,将添加一个新的反应性变量作为实例变量。然后,可以在帮助程序中访问此变量,并在事件处理程序中设置该变量。
事件处理程序接收事件对象和模板实例作为参数,并将数据上下文设置为this指针;因此,tpl.tabIdx引用反应性变量,this引用表示单击选项卡的对象(例如,
{
idx: 0,
name: "info",
title: "Personal Info",
template: "ProfilePersonal"
}对于第一个选项卡,因为这是第一个选项卡呈现时模板的数据上下文。
助手函数使用对Template的调用来获取Template.instance()实例。然后,它查询反应性数组的值。
这将在反应性上下文中创建计算(帮助器是反应性上下文,当它们创建的计算无效时,它们将重新运行,并且在计算中读取的Mongo游标或反应变量被更改时会发生这种情况)。
因此,当在事件处理程序中设置了反应性变量时,将重新运行帮助程序,并且模板反映新的值。
这些都是流星的基础,并在完整的流星文献和许多资源中加以解释。
https://stackoverflow.com/questions/34151070
复制相似问题