Created
July 13, 2010 22:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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' %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- app/views/items/index.html.erb --> | |
<div id="my_items_list"> | |
<%= render :partial => 'items', :object => @items %> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Posted about this here.