Hey all,
I’m trying to implement a feature where the client may select how to sort a list returned by a publication. In my case, switching between “top posts” and “most recent” posts. The way I’m doing it is to set a ReactiveVar inside the “user_posts” template, and toggle it on clicking a DOM element. The following code is inside the template’s onCreated function:
Template.user_posts.onCreated(function userPostsOnCreated() {
this.subOptions = new ReactiveVar({sort: {createdAt: -1}, limit: 15}); // 'new posts'
this.toggleSortText = new ReactiveVar('top');
this.autorun(() => {
this.subscribe('userPosts.user', this.getUsername(), this.subOptions.get());
});
});
Then I have the following event:
Template.user_posts_all.events({
'click .toggle-posts-sort': function(e) {
e.preventDefault();
const currSortText = Template.instance().toggleSortText.get();
if (currSortText == 'top') {
Template.instance().subOptions.set({sort: {upvotes: -1, createdAt: -1}, limit: 15});
Template.instance().toggleSortText.set('new');
}
else if (currSortText == 'new') {
Template.instance().subOptions.set({sort: {createdAt: -1}, limit: 15});
Template.instance().toggleSortText.set('top');
}
},
});
This event toggles the text contained in the .toggle-posts-sort
class just fine (it’s just a <span>
element in my template). console.log
ging the two ReactiveVars inside the this.autorun(() => {
block indicates that the sort
parameter of subOptions
is changing appropriately to include or not include “upvotes” whenever the event is triggered. However, nothing from the subscription changes when clicking .toggle-posts-sort
(i.e. the posts don’t re-order themselves).
The guide seems to suggest that a pattern like this should work, so I’m not exactly sure where I’m going wrong. Any ideas?