Skip to content

Instantly share code, notes, and snippets.

@radzserg
Last active October 19, 2016 20:34
Show Gist options
  • Save radzserg/300ea69214c0f3df847e to your computer and use it in GitHub Desktop.
Save radzserg/300ea69214c0f3df847e to your computer and use it in GitHub Desktop.
meteor pagination class
namespace('App.data')
###
Meteor pagination class
Usage
UsersController = RouteController.extend
waitOn: ->
@page = @params.query.page || 1
@pagination = new App.data.Pagination(Users, selector, {page: @page})
Meteor.subscribe "users", @pagination.selector, @pagination.getSubscriptionOptions()
data: ->
pagination: @pagination
Then in your template
{{#each pagination.getItems}}
{{> masterItem}}
{{/each}}
{{> pagination}}
###
class @App.data.Pagination
constructor: (@collection, @selector = {}, options = {}) ->
@pageSize = options.pageSize || 10
@page = options.page || 1
@maxButtonCount = 10
@totalCountMethod = "totalCount"
@templateName = options.templateName || "pagination"
@getPageRange = () ->
@getPageCount () ->
beginPage = Math.max(0, @page - Math.ceil(@maxButtonCount / 2))
endPage = beginPage + @maxButtonCount - 1
if endPage >= @pageCount
endPage = @pageCount - 1
beginPage = Math.max(0, endPage - @maxButtonCount + 1)
[beginPage, endPage]
getItems: () ->
# Get total and assign buttons as reactive variable to template
reactivePagerButtons = new ReactiveVar(null)
@.getButtons (buttons) ->
reactivePagerButtons.set buttons
Template[@templateName].helpers
pagerButtons: ->
reactivePagerButtons.get();
@collection.find @selector
getSubscriptionOptions: () ->
limit: @pageSize
skip: (@page - 1) * @pageSize
getButtons: (cb) ->
buttons = []
@getPageCount () ->
if @pageCount < 2
return buttons
currentRoute = Router.current().route.getName()
currentParams = Router.current().route.params()
[beginPage, endPage] = @getPageRange()
while beginPage++ <= endPage
query = $.query.load(location.href).set("page", beginPage).toString()
buttons.push
label: beginPage
class: if parseInt(beginPage) == parseInt(@page) then "active" else ""
path: Router.path(currentRoute, currentParams, {"query": query})
@pagerButtons = buttons
cb(buttons) if cb
getPageCount: (cb) ->
pagination = @
unless @pageCount
Meteor.call @totalCountMethod, @collection._name, @selector, (err, total) ->
pagination.pageCount = Math.floor(total / pagination.pageSize)
cb.call pagination
else
cb.call pagination
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment