简体   繁体   中英

Where should i put javaScript function in node?

I have simple function for pagination that makes output.
1 ... 6 7 8 9 ... 21
Arguments that these function need to calculate result is current number of page and total number of pages.

But i cant put it in my view (handlebars) because {{each pageArray}} need data comming from backend if i am right.

But i cant put it in my route.js because at the moment of function call i dont know number of pages or current number. It works only if i pass fake data like total pages = 100 and current page = 5

I dont know how to make it works. I dont understand how express-paginate works for example they done it somehow...

My route.js

// View users
router.get("/show/:page", function (req, res, next) {
    var perPage = 1
    var page = req.params.page || 1

    User
        .find({})
        .skip((perPage * page) - perPage)
        .limit(perPage)
        .exec(function (err, users) {
            User.countDocuments().exec(function (err, count) {
                if (err) return next(err)
                res.render('../core/modules/users/views/userList', {
                    layout: "cmsLayout",
                    users: users,
                    current: page,
                    pages: Math.ceil(count / perPage),
                    helpers,
                    pagesArr: Array.from(Array(((Math.ceil(count / perPage)))).keys()).map(i => 1 + i),
                    pageArray: pagination


                })
            })
        })
});

My pagination function

function pagination(currentPage, nrOfPages) {
    var delta = 2,
        range = [],
        rangeWithDots = [],
        l;

    range.push(1);

    if (nrOfPages <= 1) {
        return range;
    }

    for (let i = currentPage - delta; i <= currentPage + delta; i++) {
        if (i < nrOfPages && i > 1) {
            range.push(i);
        }
    }
    range.push(nrOfPages);

    for (let i of range) {
        if (l) {
            if (i - l === 2) {
                rangeWithDots.push(l + 1);
            } else if (i - l !== 1) {
                rangeWithDots.push('...');
            }
        }
        rangeWithDots.push(i);
        l = i;
    }

    return rangeWithDots;
}

Solved by changing

pagination: pagination(current, pages)

to

pagination: pagination(page, (Math.ceil(count / perPage)))

Thanks to @iagowp for solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM