I currently have endless paging setup like so:
events_controller.rb
class EventsController < ApplicationController
respond_to :html, :js
def index
@events = Event.page(params[:page]).per(5)
respond_with(@events)
end
end
events/index.html.erb
<div id="events-container">
<%= render :partial => 'events', :locals => {events: @events} %>
</div>
events/events.html.erb
<div id="events-table-container" data-events-url="<%= current_url %>">
<table id="events-tbl">
<tbody id="events-tbl-body">
<%= render events %>
</tbody>
</table>
<%= paginate events %>
</div>
assets/javascripts/events/events_endless_paging.js
$(function() {
var isScrolledIntoView;
isScrolledIntoView = function(elem) {
var docViewBottom, docViewTop, elemBottom, elemTop;
docViewTop = $(window).scrollTop();
docViewBottom = docViewTop + $(window).height();
elemTop = $(elem).offset().top;
elemBottom = elemTop + $(elem).height();
return (elemTop >= docViewTop) && (elemTop <= docViewBottom);
};
if ($('#events-container .pagination').length) {
$(window).scroll(function() {
var url;
url = $('#events-container .pagination .next a').attr('href');
if (url && isScrolledIntoView('#events-container .pagination')) {
$('#events-container .pagination').html("<span class='working-notice'>Fetching more...</span>")
return $.getScript(url);
}
});
return $(window).scroll();
}
});
events/index.js.erb
$('#events-tbl-body').append('<%= j render(@events) %>');
<% if (@events.current_page < @events.num_pages) %>
$('.pagination').replaceWith('<%= j paginate(@events) %>');
<% else %>
$('.pagination').remove();
<% end %>
This works like a charm and all. This issue becomes when I try to integrate setTimeout ajax polling to refresh the events page.
assets/javascripts/events/event_poller.js
$(document).on('ready', function() {
App.Pollers.Event.poll();
});
App.Pollers.Event = {
frequency: 170000,
poll: function() {
setTimeout(App.Pollers.Event.request, App.Pollers.Event.frequency);
},
request: function() {
eventsRequest = $.getScript($('#events-table-container').data('events-url'));
return eventsRequest;
},
};
Removing the endless paging code above, here's what the code in the events/index.js.erb would look like for just the refresh behavior to work properly:
events/index.js.erb
$('#events-container').html('<%= j(render :partial => 'events', :locals => {events: @events}, :formats => :html) %>');
App.Pollers.Event.poll();
My challenge is getting the endless paging code and the ajax refresh code working together. If I use the ajax refresh with the endless paging code, then what ends up happening is that duplicate events are appended to the events-tbl-body element. Another issue is let's say a user scrolls down the page and the endless paging appends page 2 results to page 1 results, then how does the ajax refresh code know how to display both pages 1 and 2? These are just a few of the challenges. Hoping that someone can provide guidance. I know this is a verbose question, so appreciate your attention.