Reputation: 4305
I am currently using Express with node and I am running into an issue when trying to use a custom module from inside one of my route functions. Here is what I have so far.
In my app.js file I require the module like so.
c_controller = require( './core/c_controller' );
I know this is required correctly because I console logged it out and it shows up fine.
The c_controller module looks like this.
var c_controller = {
styles: [],
script: '',
view: ''
};
c_controller.add_style = function( style ) {
this.styles.push( style );
return this;
},
c_controller.set_script = function( script ) {
this.script = script;
return this;
},
c_controller.set_view = function( view ) {
this.view = view;
return this;
},
c_controller.render = function() {
return { script: this.script,
styles: this.styles,
view: this.view };
}
exports.add_style = c_controller.add_style;
exports.set_script = c_controller.set_script;
exports.set_view = c_controller.set_view;
exports.render = c_controller.render;
The error that appears is 500 ReferenceError: c_controller is not defined.
Now im not sure if I have to pass the c_controller object into my route functions, either way im not sure how to do this.
I anyone could explain this to me to make it clearer that would be great.
Thanks in advance.
UPDATE
Here is the code that uses the c_controller
/*
* GET home page.
*/
exports.index = function(req, res){
c_controller.set_view( 'index' );
res.render( 'includes/overall_template', { c_controller.render() } );
};
Now if I require the c_controller directly into the route it works. I would rather only require the module in the main app file so I will not have to do this in every route. Does anyone know if this is possible??
Upvotes: 0
Views: 553
Reputation: 13598
To try and summarize all the comments, and what you yourself @DavidJones said:
From within your custom view, c_controller
is not known. You would have to either require
it in the view's module or even in the view function itself. You could also pass it to the view class, but I that complicates thing, and much prefer requiring.
What @Linus said -- think about exporting your whole object (not just the function), or use bind
otherwise.
Upvotes: 0
Reputation: 24291
Since you use this
inside your functions in c_controller
and you then assign only the functions to the export object, your functions will reference export
when you write this
and not c_controller
.
I think the best way to fix it is to export the entire c_controller
object, like this:
module.exports = exports = c_controller;
If you want the styles
, script
and view
variables hidden you can either:
c_controller
instead of this
exports.add_style = c_controller.add_style.bind(c_controller)
Upvotes: 1