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

Hello everybody,

now my fourth attempt to implement history.js in a Rails application. I have one approach that works quite fine, but the code is so ugly. Today I looked at the code again and thought: “How can I do it better, easier, more DRY?”

What I have done so far (and work quite fine, not perfect):

  • Install remote: truein my links
  • jquery-ujs retrieves js.erb

My HTML looks like this:

<body>
  <div id="content">
    some content with buttons, etc.
  </div>
</body>

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 this function and gives it the data. Thus, it replaces content-div with the new generated code. And it also updates the URL. I need to put this code in each (!) js.erbFile.

My last thoughts to make it a little less ugly were:

  • Install remote: truein my links
  • js.erb, content -div
  • data-remote="true" ajax:success -handler
  • ajax:success URL- history.js

. JavaScript:

$(document).on('ajax:success', 'a[data-remote="true"]', function() { ... });

: ajax:success , div -tag, ( ).

, - ...

?

+5
4

jquery-ujs pushState, popState.

:

fooobar.com/questions/1109327/...

+2

:

History.Adapter.bind(window, 'statechange', function() {
    var state = History.getState();
    ...
});
0

I use the beforeSend event as a global listener for all deleted data to change the browser history descriptor. I prefer beforeSend because I want the link to change as soon as it is clicked, regardless of the result of the ajax request ...

$(document).bind('ajax:beforeSend', function(event,data){
    history.pushState(null, '', event.target.href)
});

This solves your problem because the event is fired before any DOM modification is performed.

0
source

Have you tried turbolinks ? It will be used by default in Rails 4.

-2
source

All Articles