forked from 1602/railway-pagination
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (68 loc) · 2.81 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/** File Name: node_modules/railway-pagination/index.js
* Purpose: railway-pagination main file.
* Original author: Anatoliy C.
*
* Update History
* Name Date Description
* --------------- ---------- ------------------------------------------------------------------------------
* Jude L. 04/26/2012 - Updated the paginateCollection to allow the passing of order option to the Model.all routine.
* Jude L. 05/19/2012 - Updated the paginateCollection to allow the passing of where option to the Model.all routine
if one is provided.
**/
exports.init = function () {
// add view helper
railway.helpers.HelperSet.prototype.paginate = paginateHelper;
// add orm method
// sorry, jugglingdb only for now
railway.orm.AbstractClass.paginate = paginateCollection;
};
// global view helper
function paginateHelper(collection) {
if (!collection.totalPages || collection.totalPages < 2) return '';
var page = parseInt(collection.currentPage, 10);
var pages = collection.totalPages;
var html = '<div class="pagination">';
var prevClass = 'prev' + (page === 1 ? ' disabled': '');
var nextClass = 'next' + (page === pages ? ' disabled': '');
html += '<ul><li class="' + prevClass + '">';
html += railway.helpers.link_to('← Previous', '?page=' + (page - 1));
html += '</li>';
for (var i = 1; i <= pages; i++ ) {
if (i == page) {
html += '<li class="active"><a href="#">' + i + '</a></li>';
} else {
html += '<li>' + railway.helpers.link_to(i, '?page=' + i) + '</li>';
}
}
html += '<li class="' + nextClass + '">';
html += railway.helpers.link_to('Next →', '?page=' + (page + 1));
html += '</li></ul></div>';
return html;
};
// orm method
function paginateCollection(opts, callback) {
var limit = opts.limit || 10;
var page = opts.page || 1;
var order = opts.order||'1';
var where = opts.where;
var Model = this;
Model.count(function (err, totalRecords) {
if (where != null) {
Model.all({limit: limit, offset: (page - 1) * limit, order: order, where: where }, function (err, records) {
if (err) return callback(err);
records.totalRecords = totalRecords;
records.currentPage = page;
records.totalPages = Math.ceil(totalRecords / limit);
callback(null, records);
});
} else {
Model.all({limit: limit, offset: (page - 1) * limit, order: order }, function (err, records) {
if (err) return callback(err);
records.totalRecords = totalRecords;
records.currentPage = page;
records.totalPages = Math.ceil(totalRecords / limit);
callback(null, records);
});
}
});
}