Created
August 14, 2011 06:32
-
-
Save satlavida/1144644 to your computer and use it in GitHub Desktop.
Pagination using collections: Backbone.js
This file contains hidden or 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
class Pager | |
constructor: (collection, attributes) -> | |
@collection = collection | |
@currentPage = attributes.current_page | |
@totalPages = attributes.total_pages | |
@perPage = attributes.per_page | |
@totalEntries = attributes.total_entries | |
@pages = @visiblePageNumbers().map (page) => | |
page: page | |
path: @buildPath page | |
createLink: page isnt @currentPage and page isnt '...' | |
visiblePageNumbers: -> | |
innerWindow = 3 | |
outerWindow = 0 | |
windowFrom = @currentPage - innerWindow | |
windowTo = @currentPage + innerWindow | |
if windowTo > @totalPages | |
windowFrom -= windowTo - @totalPages | |
windowTo = @totalPages | |
if windowFrom < 1 | |
windowTo += 1 - windowFrom | |
windowFrom = 1 | |
windowTo = @totalPages if windowTo > @totalPages | |
visible = [1..@totalPages] | |
leftGap = [Math.min(2 + outerWindow, windowFrom)...windowFrom] | |
rightGap = [Math.min(windowTo + 1, @totalPages - outerWindow)...(@totalPages - outerWindow)] | |
if leftGap.length > 1 | |
visible = _(visible).reject (page) -> _(leftGap).include(page) | |
visible.splice(outerWindow + 1, 0, '...') | |
if rightGap.length > 1 | |
visible = _(visible).reject (page) -> _(rightGap).include(page) | |
visible.splice(visible.length - outerWindow - 1, 0, '...') | |
visible | |
render: -> if @totalPages > 1 then JST.pager(this) else '' | |
buildPath: (page) -> | |
"#/#{ _([ @collection._filter, page ]).compact().join('/') }" | |
isFirstPage: -> @currentPage == 1 | |
isLastPage: -> @currentPage == @totalPages | |
prevPath: -> @buildPath @currentPage - 1 | |
nextPath: -> @buildPath @currentPage + 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment