How can I react to just the URL's hash changing with Iron Router?
I've reimplemented the action
method in a custom route controller, in order to control page rendering, however this hook doesn't get invoked if only the URL's hash changes (f.ex. due to the user clicking a link with href="#about"
). The relevant part of my controller looks like this:
@UserController = RouteController.extend({
action: ->
tabName = @params.hash
@state.set("activeTab", tabName)
@render("user")
})
So, basically I need the action
method to get called whenever the URL hash changes.
It is possible to rerun the route handler when the hash changes, it just doesn't happen by default. In order to make this happen, call getParams()
on the controller instead of just accessing params
:
@UserController = RouteController.extend({
action: ->
tabName = @getParams().hash
@state.set("activeTab", tabName)
@render("user")
})
getParams
is a reactive computation that depends on the hash, so since the action
method of the controller is itself reactive, it will get re-run upon hash change.