[英]Node / Express, including custom modules
我目前在節點上使用Express,並且嘗試從我的一個路由功能中使用自定義模塊時遇到問題。 這是我到目前為止所擁有的。
在我的app.js文件中,我需要像這樣的模塊。
c_controller = require( './core/c_controller' );
我知道這是正確的要求,因為我已將其注銷並顯示正常。
c_controller模塊如下所示。
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;
出現的錯誤是500 ReferenceError:未定義c_controller。
現在我不確定是否必須將c_controller對象傳遞給我的路由函數,無論哪種方式,我都不確定如何執行此操作。
我誰都可以向我解釋這一點,以使其更加清楚。
提前致謝。
更新
這是使用c_controller的代碼
/*
* GET home page.
*/
exports.index = function(req, res){
c_controller.set_view( 'index' );
res.render( 'includes/overall_template', { c_controller.render() } );
};
現在,如果我需要直接將c_controller放入路由,則可以正常工作。 我寧願只需要主應用程序文件中的模塊,這樣就不必在每條路線中都這樣做。 有人知道這是否可能嗎?
由於在c_controller
的函數內部使用了this
函數,然后僅將函數分配給了導出對象,因此編寫this
函數時,函數將引用export
,而不是 c_controller
。
我認為解決此問題的最佳方法是導出整個c_controller
對象,如下所示:
module.exports = exports = c_controller;
如果要隱藏styles
, script
和view
變量,則可以:
c_controller
代替this
exports.add_style = c_controller.add_style.bind(c_controller)
為了嘗試總結所有評論,以及您自己的@DavidJones說:
從您的自定義視圖中, c_controller
是未知的。 您可能require
在視圖的模塊中甚至在視圖函數本身中都require
它。 您也可以將其傳遞給視圖類,但是我使事情變得復雜,並且更喜歡要求。
@Linus所說的-考慮導出整個對象(而不僅僅是函數),否則請使用bind
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.