I'm building a Rails 4 application and I'm trying to combine location.hash Backbone History with turbolinks push state. The application is broken up into multiple smaller, SPA like pages.
Example of Problem
The problem I'm having is that when I do Backbone.Router.navigate()
, within
a page, it doesn't register anything with turbolinks. Here's a hypothetical
example to demonstrate the problem:
- Visit
/one
@router.navigate 'page-one'
- Location becomes
/one#page-one
@router.navigate 'page-two'
- Location becomes
/one#page-two
- Click on link to
/two
- Turbolinks intercepts and navigates to
/two
- Click on the Back Button, you are still stuck on
/two
- Click on the Back Button again, you are still stuck on
/two
- Click on the Back Button a third time, you are brought back to
/one
What I Tried
I guessed that what's probably happening is that when navigating via backbone,
the browser is logging the change but turbolinks isn't. I tried to expose
Turbolinks.reflectNewUrl
:
@Turbolinks = { visit, pagesCached, reflectNewUrl }
And then modifying Backbone.Router.navigate
so that it registers with
turbolinks every time we navigate:
navigate = Backbone.Router.prototype.navigate
Backbone.Router.prototype.navigate = (page, args...) ->
navigate page, args...
window?.Turbolinks?.reflectNewUrl "##{page}"
That sort of worked, Step 8 above is no longer stuck on /two
, but
click on the back button again and we get this error:
Uncaught TypeError: Cannot call method 'getElementsByTagName' of null turbolinks.js:142
removeNoscriptTags turbolinks.js:142
changePage turbolinks.js:111
fetchHistory turbolinks.js:69
(anonymous function) turbolinks.js:390
So something is still wrong.
Now I'm hoping there's a kind soul out there to help me out and point out my perhaps obvious blunder :)