Reputation: 55263
I have Chapters
collection, and I show a list of chapters in one of the templates:
<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>
As you can see, I created a isCurrentChapter
to use like this:
// 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";
}
}
});
The problem now is that the active
is returned only changes when the page loads.
How can I do it so that isCurrentChapter
becomes reactive? Fires up on the click .open-chapter
event?
Upvotes: 1
Views: 1413
Reputation: 2200
To make helper reactive, it must depend on reactive source. We can use 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";
}
}
});
When session "currentChapter" changes, the helper isCurrentChapter re-runs.
EDIT: If you want to set active class on page load or refresh you can do something like this:
var currentChapterId = Session.get("currentChapter") || localStorage.getItem("currentChapter");
Try to get currentChapter from session, if it's undefined, then get it from localStorage. Or use Session.setDefault on top of your code:
Session.setDefault('currentChapter', localStorage.getItem('currentChapter'));
Upvotes: 2