Skip to content

Instantly share code, notes, and snippets.

@nowk
Created July 4, 2012 16:24
Show Gist options
  • Save nowk/3048141 to your computer and use it in GitHub Desktop.
Save nowk/3048141 to your computer and use it in GitHub Desktop.
Knockout pagination
/ ko with: paginate
.will_paginate
%span.per_page_options
Show rows
%select.per_page{:name => "per_page", 'data-bind' => 'options: per_page_limits, value: per_page'}
 
%span.go_to_page_options
Go to
%input{:name => 'page', :type => 'text', :size => "2", 'data-bind' => 'value: page, valueUpdate: "afterKeyDown"'}
 
%span
of
%strong{'data-bind' => 'text: total_pages'}
 
%span.btn-group
%button.btn{'data-bind' => 'click: go_to_prev_page'}
«
%button.btn{'data-bind' => 'click: go_to_next_page'}
»
/ /ko
// Include this mapping to enable pagination via knockout
// 'paginate': {
// create: function(options) {
// return new paginationViewModel(options.data);
// }
// }
// TODO reference to "ViewModel" will need to be dynamic
var paginationViewModel = function(data) {
this.per_page_limits = ko.observableArray([1, 30, 60, 100, 200, 300]);
ko.mapping.fromJS(data, {}, this);
var self = this;
self.go_to_prev_page = function() {
if (self.prev_page() && self.prev_page() < self.page()) {
paginate({}, self.prev_page(), self.per_page());
}
}
self.go_to_next_page = function() {
if (self.next_page() > self.page()) {
paginate({}, self.next_page(), self.per_page());
}
}
}
$('select.per_page:focus').live('change', function() {
paginate({}, 1, $(this).val());
});
$("input[name='page']").live('keypress', function(evt) {
if (evt.which == 13 && ViewModel.paginate().total_pages() > 1) {
paginate({}, $(this).val(), ViewModel.paginate().per_page());
}
});
// This method needs to be created for each till we find a easy solution
// to replicate it for each proper resource
// var paginate = function(attrs, page, per_page) {
// attrs.per_page = per_page;
// attrs.page = page;
// $.getJSON("#{path_to_get}.json", attrs, function(data) {
// ko.mapping.fromJS(data, viewModel, ViewModel);
// });
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment