在rails中使用kaminari进行无休止的滚动

时间:2015-12-26 19:11:07

标签: javascript jquery ruby-on-rails kaminari

我正在尝试使用kaminari在我的rails应用程序中实现无限滚动。它按预期工作,但如果我上下移动滚动条几次,它会一次又一次地加载,直到我停止滚动。

这是我的 pagination.js.coffee

$ ->
  content = $('#listings')    # where to load new content
  viewMore = $('#view-more') # tag containing the "View More" link

  isLoadingNextPage = false  # keep from loading two pages at once
  lastLoadAt = null          # when you loaded the last page
  minTimeBetweenPages = 5000 # milliseconds to wait between loading pages
  loadNextPageAt = 10      # pixels above the bottom

  waitedLongEnoughBetweenPages = ->
    return lastLoadAt == null || new Date() - lastLoadAt > minTimeBetweenPages

  approachingBottomOfPage = ->
    return $(document).scrollTop() < document.body.offsetHeight - loadNextPageAt

  nextPage = ->
    url = viewMore.find('a').attr('href')

    return if isLoadingNextPage || !url

    viewMore.addClass('loading')
    isLoadingNextPage = true
    lastLoadAt = new Date()

    $.ajax({
      url: url,
      method: 'GET',
      dataType: 'script',
      success: ->
        viewMore.removeClass('loading');
        isLoadingNextPage = false;
        lastLoadAt = new Date();
    })

  # watch the scrollbar
  $(window).scroll ->
    if approachingBottomOfPage() && waitedLongEnoughBetweenPages()
      nextPage()

  # failsafe in case the user gets to the bottom
  # without infinite scrolling taking affect.
  viewMore.find('a').click (e) ->
    nextPage()
    e.preventDefault()

search.html.erb

  <div id="listings">
                  <%= render 'pages/listings' %>
                </div>
                <% unless @rooms.current_page == @rooms.total_pages %>
                    <p id="view-more">
                      <%= link_to('View More', url_for(page: @rooms.current_page + 1)) %>
                    </p>
                <% end %>

search.js.erb

$('#listings').append("<%=j render('pages/listings') %>");

<% if @rooms.current_page == @rooms.total_pages %>
$('#view-more').remove();
<% else %>
$('#view-more a').attr('href', '<%= url_for(page: @rooms.current_page + 1) %>');
<% end %>

有人能告诉我这里有什么问题吗?

0 个答案:

没有答案