Javascript-форум (https://javascript.ru/forum/)
-   Node.JS (https://javascript.ru/forum/node-js-io-js/)
-   -   Как получить доступ к get-параметру внутри модуля? (https://javascript.ru/forum/node-js-io-js/59529-kak-poluchit-dostup-k-get-parametru-vnutri-modulya.html)

femalemoustache 15.11.2015 15:35

Как получить доступ к get-параметру внутри модуля?
 
Пишу простой модуль pagination для приложения на Express.js:

var config = require('../config');

function Pagination(options) {
    this.param  = options.param || 'page';
    //this.current = ?
    this.perPage = options.perPage || config.perPage;
    this.numPages = Math.ceil(options.numRows / this.perPage);
    this.prevPage = null;
    this.nextPage = null;
    this.hasPrevPage = function() {
        return (this.current > 1 && this.numPages);
    }
    this.hasNextPage = function() {
        return (this.numPages > this.current);
    }

    if (this.hasPrevPage()) {
        this.prevPage = this.current - 1;
    }

    if (this.hasNextPage()) {
        this.nextPage = this.current + 1;
    }
}

module.exports = Pagination;


В this.current мне нужно получить значения параметра, передающего страницу в постраничной навигации. Например для урла /posts/?page=3 this.current должно быть 3.

Пример применения модуля:

/app.js:

//...
var postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);


/routes/posts.js:

var express       = require('express');
var Pagination    = require('../core/pagination');
var config        = require('../config');

var router = express.Router();

router.get('/', function(req, res) {
    //...
    pagination = new Pagination({
        numRows: dbresult.count
    });

    res.render('posts', {posts: dbresult.rows, pagination: pagination});
});


Я знаю, что можно получить значение параметра внутри обработчика роута и передавать в качестве аргумента в конструктор Pagination. Я хочу, чтобы модуль получал значение сам, без необходимости каждый раз передавать его из кода в обработчике роута.


Часовой пояс GMT +3, время: 18:20.