Hi guys I'm having a small problem with an application layout. I'm setting my controllers up like this.
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);
};
And in my routes file I'm doing this.
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;
};
The app variable I'm passing is not showing up in the other instance methods. Is there a reason for this that I'm missing? Thanks for any help.
In the past I've set my controllers up like this.
module.exports = function(app) {
var controller = {
//app is defined
res.render('index', {
title: "Index"
});
}
};
return controller;
};
But I like this other pattern more and I'm more curious then anything why it won't work.
Try changing these lines:
app.get('/', Application.index);
app.get('/blah', Application.blah);
to:
app.get('/', Application.index.bind(Application));
app.get('/blah', Application.blah.bind(Application));
Your routes aren't being called in the context of your Application
instance otherwise.