Meteor: Modify collection on a route change using Iron Router


#1

So I’m working on a forum type app. When the user navigates to a post, the url will be www.myapp.com/post/POSTID. I’m using Iron Router to handle the routing.

Upon entering AND leaving this post, I want to update a collection to indicate that the user has seen the post. I know that in Iron Router, if you modify one of the underlying subscriptions that the route is subscribed to, you run into an infinite reactivity loop. I was trying to update the collection in action() before, but got an infinite loop.

So I moved the update to onRun() in the route. The infinite loop is gone, but the problem with onRun() is that it won’t trigger on hot reload. Every time I make a code change and Meteor hot reloads, the onRun() code is not called. I have to manually do a ctrl-R reload of my browser to get the onRun() code to be actually called.


#2

Yea this is the largest problem with using iron router and it’s reactivity. The onRun function is also buggy… i’ve had issues with it not firing at all in edge cases.

I’d also warn that doing this (adding business logic to a reactive route) can burry you when trying to debug (i’ve found out by doing it myself).

Here’s how I would solve the problem. On the page template onRendered callback, call the update there instead. You’ll have to grab the params from the template but you’ll have much more control.

In general moving business logic out of the router is a win.

Template.postPage.onCreated(function(){
  var postId = getPostId();
  Posts.update({_id: postId}, {$set: ... });
});


#3

Thanks, I just moved my stuff to the onRendered part of my templates. It worked.