Skip to content

Instantly share code, notes, and snippets.

@danielpcox
Created July 13, 2010 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpcox/474700 to your computer and use it in GitHub Desktop.
Save danielpcox/474700 to your computer and use it in GitHub Desktop.
a DRY and unobtrusive way to use will_paginate with ajax via jQuery
<!-- app/views/items/_items.html.erb -->
<ul>
<% items.each do |item| %>
<li><%= item.name %></li>
<% end %>
</ul>
<%= ajax_will_paginate items, :update => 'my_items_list' %>
// public/javascripts/application.js
function rebind_pagination_listener() {
$('.pagination.ajax a').click(function(e) {
$('#'+e.target.parentNode.getAttribute('update')).load(e.target.href);
// anything else you want to happen when the pagination links are clicked goes here
e.preventDefault();
})
}
# app/helpers/application_helper.rb
def ajax_will_paginate(collection, options={})
options.merge!({:class => 'pagination ajax'})
output = will_paginate(collection, options)
output += "<script lang='javascript'>rebind_pagination_listener()</script>".html_safe if output
output
end
<!-- app/views/items/index.html.erb -->
<div id="my_items_list">
<%= render :partial => 'items', :object => @items %>
</div>
# app/controllers/items_controller.rb
def index
@items = Item.all
respond_to do |format|
format.html
format.js do
render :partial => 'items', :object => @items.paginate(:page => params[:page], :per_page => 5)
end
end
end
@danielpcox
Copy link
Author

Posted about this here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment