I did something like what you want, I think. I have a publish for the search query:
Meteor.publish("search", function (query) {
var re = new RegExp(query, 'i');
return Chart.find({"demographics.lastName": {$regex: re}}, {limit: 200, sort: {"demographics.lastName": 1}});
});
the helpers for the template to display the results:
Template.searchResults.helpers({
searchString: function () {
return Session.get('searchString');
},
theCharts: function () {
var query = Session.get('searchString');
searchSubsManager.subscribe("search", query);
var re = new RegExp(query, 'i');
var chartsFound = Chart.find({"demographics.lastName": {$regex: re}}, {limit: 200, sort: {"demographics.lastName": 1}});
return chartsFound;
}
});
and here’s the trick, using the SubsManager:
var searchSubsManager = new SubsManager({
// keep the last 3 searches run
cacheLimit: 3,
expireIn: 5
});
as the comment says, doing this will only keep the last 3 searches on the client. Also, it will expire the search after 5 minutes as well.
Keeping the last 3 allows me to have someone search for, say Anders, then Anderson, then go back to Anders, and it will only hit the server twice, when the user goes back to Anders, it already has that result subscribed to and doesn’t go back to the server. Then, after 5 minutes, no updates will be sent to the client because the sub will be expired automatically.
to complete the example, I have this route:
Router.route('/search', {
action: function () {
this.render('searchResults');
}
});
and the submit on the search form does this:
'submit #searchForm': function (e) {
e.preventDefault();
var searchString = e.target.liveSearch.value;
Session.setPersistent('searchString', searchString);
Router.go('/search');
}
Note: my solution doesn’t use autorun.
This works because the Session variable is reactive, so all I have to do is set the search string into the session on the submit event, then route to the search route, and the helper takes care of doing the subscription and finding the results.