Reputation: 782
I am trying to update the id passed to a subscribe parameter in Meteor - in short, I am wanting to subscribe to whatever the Collection object is with the id in the current url. I can get this to happen for first load, but not when a new object is created and the user is routed to that new object within their session.
The only way I have been able to get this to vaguely work is a hack using setInterval
- not great I know, so am looking for the correct Meteor way.
Currently my publications.js
in server
is:
Meteor.publish('shares', function(id){
return Shares.find({_id:id});
});
router.js
is
Router.route('/share-social/:_id', {
name: 'shareSocial',
data: function() { return Shares.findOne(this.params._id); }
});
and subscribing via main.js
in client
: (ie, get the id in the url, and subscribe to that)
setInterval(function(){
var x = location.href.split('/');
var id = x.slice(-1).pop();
Meteor.subscribe('shares', id);
}, 100);
and finally the template helper:
Template.shareSocial.helpers({
shares: function() {
return Shares.find().fetch();
}
});
The above clearly has its issues. How do I reactively subscribe only to the object with the id that is displayed in the current url, whether it be in the same session or new session?
Thanks!
Upvotes: 1
Views: 202
Reputation: 66
Instead of slicing the id from the URL, you could set up a reactive source for your subscription by defining current id to a Session variable, e.g.:
// router.js
Router.route('/share-social/:_id', function() {
Session.set('id', this.params._id);
this.render('shareSocial');
});
// main.js
Tracker.autorun(function() {
Meteor.subscribe('shares', Session.get('id'));
});
Now every time you change the id for your route, both the Session variable and subscription will be updated.
Upvotes: 0