在控制器内部的app对象上嵌入属性或方法

时间:2014-03-17 17:58:08

标签: javascript kraken.js

我正在尝试在kraken.js应用程序中关联app对象上的方法或属性,如下所示:

控制器/ index.js

'use strict';

var IndexModel = require('../models/index');


module.exports = function (app) {

    var model = new IndexModel();
    app.get('/', function (req, res) {
        console.log(app.adventurer);
        /* Console should be showing "Bilbo Bagins", but I'm getting 'undefined'.
         * See the next source file. */
        res.render('index', model);        
    });

};

/index.js

var kraken = require('kraken-js'),
    app = {
        adventurer: 'Bilbo Bagins'
    };


app.configure = function configure(nconf, next) {
    // Async method run on startup.
    next(null);
};


app.requestStart = function requestStart(server) {
    // Run before most express middleware has been registered.
};


app.requestBeforeRoute = function requestBeforeRoute(server) {
    // Run before any routes have been added.
};


app.requestAfterRoute = function requestAfterRoute(server) {
    // Run after all routes have been added.
};


if (require.main === module) {
    kraken.create(app).listen(function (err) {
        if (err) {
            console.error(err.stack);
        }
    });
}


module.exports = app;

此外,我已尝试在/config/app.json

上发布该媒体资源

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

只需将以下密钥添加到.config / app.json或创建一个新的.config / app-development.json:

"adventurer": "bilbo"

app.json将如下所示:

{
//blah
//blah
"adventurer": "bilbo"
}

然后在./index.js中执行以下配置:

app.configure = function configure(nconf, next) {
    // Async method run on startup.
    next(null);
    console.log('my traveler is: ', nconf.get('adventurer'));
};

在回复您的评论时,如果您想从./controllers/index.js获取应用程序配置,则需要nconf lib并使用nconf.get,如下所示:

'use strict';
var nconf = require('nconf');

var IndexModel = require('../models/index');

module.exports = function (app) {

    var model = new IndexModel();

    //or attach it directly to the app object like so
    app.set('adventurer', nconf.get('adventurer'));
    console.log('adventurer directly set on app object', app.get('adventurer'));

    console.log('controller with app adventurer:', nconf.get('adventurer'));

    app.get('/', function (req, res) {

        res.render('index', model);

    });

};

使用npm start启动并观察控制台。和平!