无限滚动和will_paginate追加“下一页”的项目多次(Infinite scroll and

2019-07-04 03:31发布

我下面这个railscast试图在我的Rails应用程序实现一个无限滚动页面。 当用户向下滚动到页面底部的新组项目的追加和页面扩展,但它是附加在页面多次和事件上,即使在阵列中的所有项目都被加载下滚再次触发,多次追加再次同组项目。

我想是的“下一页”用户每次滚动至底部,以及随后的下一个页面当用户滚动至底部再次追加项目。

这里是jQuery的这个函数:

jQuery ->
  if $('.pagination').length
          $(window).scroll ->
                  url = $('.pagination .next_page').attr('href')
                  if url &&  $(window).scrollTop() > $(document).height() - $(window).height() - 50
                      $('.pagination').text('Fetching more products...')
                      $.getScript(url)
$(window).scroll()

这里是相应的JavaScript

$('#products').append('<%= j render(@products) %>');
<% if @products.next_page %>
    $('.pagination').replaceWith('<%= j will_paginate(@products) %>');
<% else %>
    $('.pagination').remove();
<% end %>

Answer 1:

Your code will trigger a $.getScript(url) call when the user scrolls to 50px from the bottom. Then another call at if they scroll to 49px from the bottom. Then another if they scroll to 48px from the bottom and this will continue until one of the AJAX calls returns and makes the page taller; once the page is taller, you'll be outside the 50px zone and the Fetching more products... will stop.

You only want one getScript going at a time. Once they scroll into the 50px zone, you want to fetch some more stuff from the server (just once) then ignore subsequent scrolls until the server has responded.

You should be doing something more like this:

$(window).scroll ->
    # Bail out right away if we're busy loading the next chunk.
    return if(window.pagination_loading)

    url = $('.pagination .next_page').attr('href')
    if url &&  $(window).scrollTop() > $(document).height() - $(window).height() - 50
        # Make a note that we're busy loading the next chunk.
        window.pagination_loading = true

        # Load as before but attach a callback to clear the flag when we're done.
        $('.pagination').text('Fetching more products...')
        $.getScript(url).always -> window.pagination_loading = false

$.getScript returns a jqXHR and the jqXHR's always callbacks will be called when the underlying $.ajax call is finished.



文章来源: Infinite scroll and will_paginate appending the 'next page' of items multiple times