Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do history.js in Rails the right way?

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?

like image 668
Benjamin M Avatar asked Nov 25 '22 00:11

Benjamin M


1 Answers

I only use jquery-ujs and pushState, popState.

See my answer here:

https://stackoverflow.com/a/27532946/345996

like image 120
jogaco Avatar answered Dec 19 '22 12:12

jogaco