How to configure template to rerender when going back using browser back button?


I have created a pagination with configurable limit. I am getting
page number from the IronRouter. The code works when I enter url
manually with different page numbers. However, when I use go back with
browser back button, it does change the url and I can see beforeaction and action being logged to console but it doesn’t trigger template update/re-render.

Iron route is defined as follow:

@route "/posts/page/:pageNum",
    name: ""
    template: "posts"
    layoutTemplate: "default_layout"
    onBeforeAction: () ->
      console.log 'beforeaction', @params.pageNum, @
    action: () ->
      console.log 'inside action', @, @state.get 'pageNum'

Template onCreated code:

Template.posts.onCreated ->
  limit = 10
  currPage = Router.current().state.get('pageNum') || 1

  self = @
  @itemsPerPage = new ReactiveVar limit
  @currPage = new ReactiveVar parseInt currPage, 10

  @autorun ->
    handle = self.subscribe "posts",
      limit: self.itemsPerPage.get()
      ,page: self.currPage.get()

Navigation code that updates the posts but doesn’t update when using browser back button:

'click .pager-page': (e,t) ->
  gotoPage = parseInt e.currentTarget.dataset.pagerPage, 10
  t.currPage.set gotoPage
  Router.go '', pageNum: gotoPage


Update and re-render are two different things. Meteor never re-renders templates. It renders them, then updates only the parts that have changed. In your specific case, @itemsPerPage is initialized, but it does not change when your route changes.


Just move the code from onCreated to onRendered, that should solve it.

And unrelated hint:

  self = @
  @autorun ->
    handle = self.subscribe "posts",
      limit: self.itemsPerPage.get()
      ,page: self.currPage.get()

can be written as

  @autorun =>
    handle = @subscribe "posts",
      limit: @itemsPerPage.get()
      ,page: @currPage.get()

by using the fat arrow (see for description; it’s basically an ES6 closure, i.e. retains the this from the outer context).


Thanks for the tip @seeekr
I solved the issue using Router.current().state API
I posted details here

Thanks for you help.