javascript - NodeJS 应用程序布局和变量传递

标签 javascript node.js

大家好,我在应用程序布局方面遇到了一个小问题。我正在这样设置我的 Controller 。

ApplicationController = function(_app) {
    this.app = _app;
    console.log(this.app); //this works
};

ApplicationController.prototype.index = function(req, res, next) {
    console.log(this.app); //this is undefined
    res.json("hello");
};

module.exports = function(app) {
    return new ApplicationController(app);
};

在我的路线文件中,我正在这样做。

module.exports = function(app) {

    //require controllers
    var Application = require('./controllers/ApplicationController')(app);       


    //define routes
    app.get('/', Application.index);
    app.get('/blah', Application.blah);

    return app;
};

我传递的 app 变量没有出现在其他实例方法中。有没有我失踪的原因?感谢您的帮助。

过去我是这样设置我的 Controller 的。

module.exports = function(app) {

    var controller = {

            //app is defined
            res.render('index', {
                title: "Index"
            });
        }
    };

    return controller;
};

但我更喜欢这种其他模式,而且我更好奇为什么它不起作用。

最佳答案

尝试更改这些行:

app.get('/', Application.index);
app.get('/blah', Application.blah);

到:

app.get('/', Application.index.bind(Application));
app.get('/blah', Application.blah.bind(Application));

否则,您的路由不会在您的 Application 实例的上下文中被调用。

关于javascript - NodeJS 应用程序布局和变量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10817636/

相关文章:

javascript - $(selector).on() 中的 jQuery 未捕获类型错误

javascript - 窗口大小调整功能

javascript - Javascript 中不包括连字符的单词边界

javascript - KineticJs 不同 Angular 旋转

node.js - TypeError : foundUser. lastLogin.update 不是一个函数

javascript - webpack 开发服务器正在监听扩展名为 PHP 的文件( "index.php")

javascript - 如何向服务器端提交一个javascript变量

javascript - 如何修复丢失的 @angular/Core 模块?

node.js - 删除非空目录

node.js - 邮件监听器2 : cannot get string 'address' from object