How to do history.js in Rails the right way?
history.js, ruby-on-rails
Solution
I only use jquery-ujs and pushState, popState.
See my answer here:
https://stackoverflow.com/a/27532946/345996
Problem
Hi everyone, it's now my fourth try to implement history.js in a Rails app. I have one approach that is running quite okay, but the code is so ugly. Today again I looked at the code and thought: How can I make this better, easier, more DRY?! What I have done so far (and working quite okay, not perfect): - Set `remote: true` to my links - jquery-ujs fetches the `js.erb` My HTML looks like: ``` <body> <div id="content"> some content with buttons, etc. </div> </body> ``` The `js.erb` contains: ``` History.pushState( { func: '$(\'#content\').html(data);', data: '<%= j(render template: "news/index", formats: [:html]) %>' }, 'test title', '<%= request.url %>' ); ``` And then history.js takes the function and gives it the data. So it replaces the `content`-div with the new generated code. And it also updates the URL. This code I have to put in every(!) `js.erb` file. My last thoughts to make it a bit less ugly were: - Set `remote: true` to my links - When a link gets clicked it fetches some `js.erb` which replaces the `content`-div - All links with `data-remote="true"` will get a `ajax:success`-handler - On `ajax:success` the new URL gets pushed to history.js But there's still one problem within. Then I have JavaScript code: ``` $(document).on('ajax:success', 'a[data-remote="true"]', function() { ... }); ``` The problem is: `ajax:success` never fires if I replace the `div`-tag where the link (that should fire the event) was in. Maybe someone can solve my problems... Or is there a better way?