1. 程式人生 > >nodejs分頁類

nodejs分頁類

上進 too pre rst proto nat 基礎上 tro 最大

改編自http://my.oschina.net/wanglihui/blog/269907,感謝原作者,我在基礎上進行了二次封裝

分頁類,我放在 plugin/Paginate.js

/**
 * 分頁插件類(缺少每頁的顯示數,listrows明天寫)
 * @param page {Number} 當前頁
 * @param pagesize {Number} 每頁記錄數
 * @param total {Number} 總記錄數
 * @constructor
 */
function Paginate(page, pagesize, total){
    if(!page || page <1){
        page = 1;
    }
    if(!pagesize || pagesize<1){
        pagesize = 20;
    }
    if(!total || total <0){
        total = 0;
    }

    this.pagesize = pagesize;
    this.total = total;
    if(this.total%this.pagesize ===0){
        this.maxpage = parseInt(this.total/this.pagesize);
    }else{
        this.maxpage = parseInt(this.total /this.pagesize) + 1;
    }

    if(page>this.maxpage){
        this.page = this.maxpage;
    }else{
        this.page = page;
    }

}


/*
* 當前開始的條數
*/
Paginate.prototype.first = function(){
    var first = (this.page-1)*this.pagesize;
    if(first>this.total){
        return (this.maxpage-1)*this.pagesize;
    }
    return first; 
}

/*
* 當前頁最大的條數
*/
Paginate.prototype.last = function(){
    var last = this.first()+this.pagesize;
    if(last>this.total){
        return this.total;
    }
    return last;
}


/**
 * 上一頁
 * @returns {number}
 */
Paginate.prototype.prev = function(){
    if(this.page <= 1){
        return false;
    }
    return this.page-1;
}


/**
 * 下一頁
 * @returns {*}
 */
Paginate.prototype.next = function(){
    if(this.page >= this.maxpage){
        return false;
    }
    return (parseInt(this.page)+1);
}

module.exports = Paginate;

使用例子

var Paginate = require("../plugin/Paginate");
var q = req.query.q;
var paginate = new Paginate(q, 10, 185);
var page = paginate.page;//當前頁數
var first = paginate.first();//當前第一條
var last = paginate.last();//當前最大條數
var maxpage = paginate.maxpage;//總頁數    
var pagesize = paginate.pagesize;//每頁顯示數
var total = paginate.total;//總記錄數
var prev = paginate.prev();//上一條
var next = paginate.next();//下一條 
res.json({page:page, first:first,last:last,maxpage:maxpage,pagesize:pagesize, total:total,prev:prev,next:next})

nodejs分頁類