Implementing an infinite scroll with Rails 3 and jQuery

I am trying to incorporate an endless scroll into my project. I use a combination of the Railscast # 114 Endless Page and this .

Everything works fine except for the weird behavior when I try to stop sending requests when the page comes to an end.

So far I:

Controller:

def show
    @title = Photoset.find(params[:id]).name
    @photos = Photoset.find(params[:id]).photo.paginate(:page => params[:page], :per_page => 20)
    respond_to do |format|
      format.js
      format.html
    end
end

Show.html.erb:

<% content_for :body_class, '' %>
<%= render 'shared/header' %>
<div id="photos_container">
    <div id="photos_header">
    <h2><%= @title %></h2>
    </div>
    <%= render :partial => 'photo', :collection => @photos %>
</div>
<%= render :partial => 'endless_scroll' %>

Javascript (loaded via partial):

<script type="text/javascript">
(function() {
  var page = 1,
  loading = false,
  finish = false;

  function nearBottomOfPage() {
    return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
  }

  function finish() {
    finish = true;
  }

  $(window).scroll(function(){
    if (loading) {
      return;
    }

    if(nearBottomOfPage() && !finish) {
      loading=true;
      page++;
      $.ajax({
        url: '/photosets/<%= params[:id] %>?page=' + page,
        type: 'get',
        dataType: 'script',
        success: function() {
          loading=false;
        }
      });
    }
  });
}());
</script>

show.js.erb

$("#photos_container").append("<%= escape_javascript(render :partial => 'photo', :collection => @photos) %>");
<% if @photos.total_pages == params[:page].to_i() %>
    page.call 'finish'
<% end %>

As you can see, on mine show.js.erbI have page.callone that sets true to a variable finish. This stops requests.

The wired thing is that it never loads the last page. When @photos.total_pages == params[:page].to_i()instead of calling a function finishand setting the variable to true, it also prevents the launch $("#photos_container").append("<%= escape_javascript(render :partial => 'photo', :collection => @photos) %>");.

, SQL, .

@photos.total_pages < params[:page].to_i(), , , .

. , (Rails) .

+5
1

html , xhr:

def show
  photoset = Photoset.includes(:photos).find(params[:id])
  @title = photoset.name
  @photos = photoset.photo.paginate(:page => params[:page], :per_page => 20)
  if request.xhr?
    render '_photo', :layout => false
  end
end

ajax-:

$.ajax({
  url: '/photosets/<%= params[:id] %>?page=' + page,
  type: 'get',
  dataType: 'script',
  success: function(response) {
    $("#photos_container").append(response);
    if (response == "") {
      //stop calling endless scroll
    }
  });  
});
+2

All Articles