I have a list of items fetched from a collection and I want to make it show different stuff depending what button is clicked. I figured I'd do this via sessions that update the publication.
Here's my publication:
Meteor.publish('stuff', function(filter) {
var nameVar = filter || "default"
return myStuff.find({name: nameVar})
})
Which I subscribe to in my router:
Router.route('/', {
name: 'home',
layoutTemplate: 'homeLayout',
waitOn: function() {
return Meteor.subscribe('stuff', Session.get('filter'));
}
});
Then make the buttons do their thing (they each have an id that matches what I want to filter by):
Template.buttonFilter.events({
'click button': function(event, template) {
var buttonId = event.currentTarget.id
Meteor.subscribe('stuff', Session.set('filter', buttonId))
}
})
However, when I click a button it won't unsubscribe from what I first subscribed to via the router, only from what was set on my last button click. I don't really understand why or how to fix it.
Edit: I don't believe this to be a duplicate since the answers to the other questions talk about changing routes, which I'm not doing.
It sounds like what you want (correct me if I'm wrong) is not so much to unsubscribe from the prior search, but to reactively subscribe to the current search and drop all records that are not encompassed by it. If so, you don't need to manually manage unsubscribing - Meteor will do that for you; you just need to make your subscription reactive.
Iron Router's waitOn
will not rerun each time the subscription changes. To do that there are a few options. The quick and dirty option is to move the subscription from waitOn
to onBeforeAction
which will be rerun each time:
Router.route('/', {
name: 'home',
layoutTemplate: 'homeLayout',
onBeforeAction: function() {
Meteor.subscribe('stuff', Session.get('filter'));
this.next(); //make sure to include
}
});
Alternatively you can do it outside the router:
Tracker.autorun(function(){
var filter = Session.get('filter');
Meteor.subscribe('stuff', filter);
});
In either case you don't need to change the subscription from template.events - just change the session value.
Template.buttonFilter.events({
'click button': function(event, template) {
var buttonId = event.currentTarget.id;
Session.set('filter', buttonId);
}
});