I'm trying to on top of paginating using ajax, use the pushState to update the url. The problem I'm having is that it only executes the first time.
My complete setup is the following
Rails 3.2,
Jquery,
Kaminari(pagination gem)
so here is the code I use for updating url
jQuery ->
$(".pagination a[data-remote=true]").on 'click', (e) ->
e.preventDefault()
history.pushState {}, '', $(this).attr("href")
And on show.js.erb, to update the content I use
$("#reviews").html('<%= escape_javascript render("review") %>')
$("#paginator").html('<%= escape_javascript(paginate(@reviews, :remote => true).to_s) %>');
The show works every time, but the first script does it only the first time.
If I put a break point on the generated script, I can see when the script is first called, it works but afterwards it is never called, as if there was some sort of unbinding I guess.
With jquery-ujs, this is what I do:
In show.html.erb:
<div id="content">
<div class="paginator">
<%= paginate @mydata, remote: true %>
</div>
<div id="mydata">
<%= render partial: 'mydata' %>
</div>
<div class="paginator">
<%= paginate @mydata, remote: true %>
</div>
</div>
In show.js.erb:
$('div#mydata').html('<%= j render partial: 'mydata' %>');
$('div.paginator').html('<%= j(paginate(@mydata, :remote => true).to_s) %>');
In application.js:
$('div#content').on('click', '.pagination a[data-remote=true]', function() {
history.pushState(null, '', $(this).attr("href"))
});
$(window).on('popstate', function () {
var remoteUrl = "<a href='" + document.location.href + "'" + " data-remote='true'></a>"
$.rails.handleRemote( $(remoteUrl) );
});
Try:
history.pushState 'data', '', $(this).attr("href")
Probably all .pagination a[data-remote=true]
links are in #paginator
container which content is updated in show.js.erb
. You need to repeat bind with on
method after html replace OR just delagate event handler from parent container [read on
documentation for details]
jQuery ->
$("#paginator").on 'click', '.pagination a[data-remote=true]', (e) ->
e.preventDefault()
history.pushState {}, '', $(this).attr("href")