为什么我的模板的 if 子句没有被动更新?



无论出于什么原因,我都无法通过无数小时的故障排除来解决这个问题。我有一些简单的助手使用Bootstrap 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}}

单击选项卡时,助手将不会重新运行,因为不会对响应数据进行更改以使计算无效。

一种更像流星的方法是添加一个反应变量来保持选项卡状态,并在事件侦听器中更改它。

<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"
}

对于第一个选项卡,因为这是呈现第一个选项卡时模板的数据上下文。

helper函数通过调用Template.instance()来获取Template实例。然后,它查询反应数组的值。

这在反应上下文中创建了一个计算(辅助对象是反应上下文,当它们创建的计算无效时,它们会重新运行,当Mongo光标或计算中读取的反应变量发生更改时,就会发生这种情况)。

因此,当在事件处理程序中设置反应变量时,助手将重新运行,模板将反映新值。

这些都是Meteor的基础,在完整的Meteor文档和许多资源中都有解释。

最新更新