我目前有无休止的分页设置,如下所示:
events_controller.rb
class EventsController < ApplicationController
respond_to :html, :js
def index
@events = Event.page(params[:page]).per(5)
respond_with(@events)
end
end
事件/index.html.erb
<div id="events-container">
<%= render :partial => 'events', :locals => {events: @events} %>
</div>
事件/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>
资产/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();
}
});
事件/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 %>
这就像一个魅力和一切。当我尝试集成 setTimeout ajax 轮询以刷新事件页面时,就会出现此问题。
资产/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;
},
};
删除上面的无休止的分页代码,下面是 events/index.js.erb 中的代码,以使刷新行为正常工作:
事件/index.js.erb
$('#events-container').html('<%= j(render :partial => 'events', :locals => {events: @events}, :formats => :html) %>');
App.Pollers.Event.poll();
我的挑战是让无尽的分页代码和 ajax 刷新代码一起工作。如果我将 ajax 刷新与无休止的分页代码一起使用,那么最终会发生重复事件被附加到events-tbl-body元素。另一个问题是假设用户向下滚动页面并且无休止的分页将第 2 页结果附加到第 1 页结果,那么 ajax 刷新代码如何知道如何显示第 1 页和第 2 页?这些只是挑战中的一小部分。希望有人能提供指导。我知道这是一个冗长的问题,所以感谢您的关注。