sync/www/assets/js/paginator.js

106 lines
3.3 KiB
JavaScript
Raw Normal View History

2013-07-31 14:57:59 +00:00
(function () {
var defaults = {
preLoadPage: function () { },
postLoadPage: function () { },
generator: function () { },
itemsPerPage: 20,
maxPages: 5
};
function P(items, opts) {
this.items = items;
this.opts = opts || {};
for(var k in defaults)
if(!this.opts[k])
this.opts[k] = defaults[k];
2014-01-08 16:57:48 +00:00
this.paginator = $("<ul/>").addClass("pagination");
2013-07-31 14:57:59 +00:00
this.loadPage(0);
}
P.prototype.loadButtons = function (p) {
2013-11-21 06:08:49 +00:00
var pages = parseInt(this.items.length / this.opts.itemsPerPage) + 1;
2013-07-31 14:57:59 +00:00
var endcaps = pages > this.opts.maxPages;
this.paginator.html("");
2014-01-08 16:57:48 +00:00
if (this.items.length < this.opts.itemsPerPage) {
this.paginator.css("margin-top", "0");
2013-07-31 14:57:59 +00:00
return;
2014-01-08 16:57:48 +00:00
}
var ul = this.paginator;
2013-07-31 14:57:59 +00:00
var s = p - parseInt(this.opts.maxPages / 2);
s = s + this.opts.maxPages < pages ? s : pages - this.opts.maxPages;
2013-08-01 19:20:50 +00:00
s = s < 0 ? 0 : s;
2013-07-31 14:57:59 +00:00
if(endcaps) {
var li = $("<li/>").appendTo(ul);
$("<a/>").attr("href", "javascript:void(0)")
.html("&laquo;")
.click(function () {
this.loadPage(0);
}.bind(this))
.appendTo(li);
if(p == 0)
li.addClass("disabled");
if(s > 0) {
var sep = $("<li/>").addClass("disabled")
.appendTo(ul);
$("<a/>").attr("href", "javascript:void(0)")
.html("&hellip;")
.appendTo(sep);
}
}
for(var i = s; i < s + this.opts.maxPages && i < s + pages; i++) {
2013-07-31 14:57:59 +00:00
(function (i) {
var li = $("<li/>").appendTo(ul);
if(i == p)
li.addClass("active");
$("<a/>").attr("href", "javascript:void(0)")
.text(i + 1)
.click(function () {
this.loadPage(i);
}.bind(this))
.appendTo(li);
}.bind(this))(i);
}
if(endcaps) {
if(s + this.opts.maxPages < pages) {
var sep = $("<li/>").addClass("disabled")
.appendTo(ul);
$("<a/>").attr("href", "javascript:void(0)")
.html("&hellip;")
.appendTo(sep);
}
var li = $("<li/>").appendTo(ul);
$("<a/>").attr("href", "javascript:void(0)")
.html("&raquo;")
.click(function () {
this.loadPage(pages - 1);
}.bind(this))
.appendTo(li);
if(p == pages - 1)
li.addClass("disabled");
}
}
P.prototype.loadPage = function (page) {
this.opts.preLoadPage(page);
this.loadButtons(page);
var s = page * this.opts.itemsPerPage;
var e = s + this.opts.itemsPerPage;
if(e > this.items.length)
e = this.items.length;
for(var i = s; i < e; i++) {
this.opts.generator(this.items[i], page, i);
}
this.opts.postLoadPage();
}
window.Paginate = function (items, opts) {
var p = new P(items, opts);
return p;
};
})();