大家好,我在应用程序布局方面遇到了一个小问题。我正在这样设置我的 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/