[英]How to make the following template helper reactive (Meteor)?
我有“ 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
事件上啟動?
為了使助手具有反應性,它必須依賴於反應性源。 我們可以使用Session。
// 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";
}
}
});
當會話“ currentChapter”更改時,幫助程序isCurrentChapter重新運行。
編輯:如果要在頁面加載或刷新時設置活動類,可以執行以下操作:
var currentChapterId = Session.get("currentChapter") || localStorage.getItem("currentChapter");
嘗試從會話獲取currentChapter,如果未定義,則從localStorage獲取。 或在代碼之上使用Session.setDefault:
Session.setDefault('currentChapter', localStorage.getItem('currentChapter'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.