Skip to content

Instantly share code, notes, and snippets.

@houoop
Created January 9, 2013 10:20
Show Gist options
  • Save houoop/4492122 to your computer and use it in GitHub Desktop.
Save houoop/4492122 to your computer and use it in GitHub Desktop.
knockout paging extend
ko.extenders.paging = function (target, pageSize) {
var _pageSize = ko.observable(pageSize || 10), // default pageSize to 10
_currentPage = ko.observable(1); // default current page to 1
target.pageSize = ko.computed({
read: _pageSize,
write: function (newValue) {
if (newValue > 0) {
_pageSize(newValue);
}
else {
_pageSize(10);
}
}
});
target.currentPage = ko.computed({
read: _currentPage,
write: function (newValue) {
if (newValue > target.pageCount()) {
_currentPage(target.pageCount());
}
else if (newValue <= 0) {
_currentPage(1);
}
else {
_currentPage(newValue);
}
}
});
target.pageCount = ko.computed(function () {
return Math.ceil(target().length / target.pageSize()) || 1;
});
target.currentPageData = ko.computed(function () {
var pageSize = _pageSize(),
pageIndex = _currentPage(),
startIndex = pageSize * (pageIndex - 1),
endIndex = pageSize * pageIndex;
return target().slice(startIndex, endIndex);
});
target.moveFirst = function () {
target.currentPage(1);
};
target.movePrevious = function () {
target.currentPage(target.currentPage() - 1);
};
target.moveNext = function () {
target.currentPage(target.currentPage() + 1);
};
target.moveLast = function () {
target.currentPage(target.pageCount());
};
return target;
};
/// -- End paging extender -- \\\
/// Sample View Model that has an observableArray extended with the paging extender
var ViewModel = function () {
this.items = ko.observableArray([{value: '1'},{value: '2'},
{value: '3'},{value: '4'},
{value: '5'},{value: '6'},
{value: '7'},{value: '8'},
{value: '9'},{value: '10'},
{value: '11'},{value: '12'},
{value: '13'}]).extend({ paging: 5 });
};
ko.applyBindings(new ViewModel());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment