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


#1

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: "posts.page"
    template: "posts"
    layoutTemplate: "default_layout"
    onBeforeAction: () ->
      console.log 'beforeaction', @params.pageNum, @
      @next()
    action: () ->
      console.log 'inside action', @, @state.get 'pageNum'
      @render()

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()
    yes

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

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

#2

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.


#3

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()
    yes

can be written as

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

by using the fat arrow (see http://coffeescript.org/#fat-arrow for description; it’s basically an ES6 closure, i.e. retains the this from the outer context).


#4

Thanks for the tip @seeekr
I solved the issue using Router.current().state API
I posted details here http://stackoverflow.com/a/30558254/1743681

Thanks for you help.