如何使以下模板助手响应式(流星)

How to make the following template helper reactive (Meteor)?

本文关键字:响应 流星 何使      更新时间:2023-09-26

我有Chapters集合,我在其中一个模板中显示了章节列表:

<template name="chapterItem">
  <div class="chapter clearfix {{isCurrentChapter}}">
    <div class="chapter-arrows">
      <a class="move-up" href="javascript:;"><i class="ion-arrow-up-a"></i></a>
      <a class="move-down" href="javascript:;"><i class="ion-arrow-down-a"></i></a>
    </div>
    <h4><a class="open-chapter" href="javascript:;">{{title}}</a></h4>
    <a class="delete-current-chapter" href="javascript:;"><i class="ion-close-circled"></i></a>
  </div>
</template>

如您所见,我创建了一个isCurrentChapter来像这样使用:

// book_page.js
Template.bookPage.events
  "click .open-chapter": function() {
    localStorage.setItem "currentChapter", this._id
  }
// chapter_item.js
Template.chapterItem.helpers({
  isCurrentChapter: function() {
    var currentChapterId = localStorage.getItem("currentChapter");
    var selectedChapterId = this._id;
    if selectedChapterId === currentChapterId) {
      return "active";
    }
  }
});

现在的问题是,仅当页面加载时,返回的active才会更改。

我怎样才能使isCurrentChapter变得被动?在click .open-chapter事件上点火?

要使帮助程序成为反应式的,它必须依赖于反应式源。我们可以使用会话。

// book_page.js
Template.bookPage.events({
  "click .open-chapter": function() {
    Session.set('currentChapter', this._id);
    localStorage.setItem("currentChapter", this._id);
  }
});
// chapter_item.js
Template.chapterItem.helpers({
  isCurrentChapter: function() {
    var currentChapterId = Session.get("currentChapter");
    var selectedChapterId = this._id;
    if (selectedChapterId === currentChapterId) {
      return "active";
    }
  }
});

当会话"当前章节"更改时,帮助程序是当前章节重新运行。

编辑:如果您想在页面加载或刷新时设置活动类,您可以执行以下操作:

var currentChapterId = Session.get("currentChapter") || localStorage.getItem("currentChapter");

尝试从会话中获取当前章节,如果未定义,则从本地存储获取它。或者在代码之上使用 Session.setDefault:

Session.setDefault('currentChapter', localStorage.getItem('currentChapter'));