簡體   English   中英

節點/ Express,包括自定義模塊

[英]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;

如果要隱藏stylesscriptview變量,則可以:

  1. 使用c_controller代替this
  2. 在導出函數之前將其綁定,如下所示: exports.add_style = c_controller.add_style.bind(c_controller)

為了嘗試總結所有評論,以及您自己的@DavidJones說:

  1. 從您的自定義視圖中, c_controller是未知的。 您可能require在視圖的模塊中甚至在視圖函數本身中都require它。 您也可以將其傳遞給視圖類,但是我使事情變得復雜,並且更喜歡要求。

  2. @Linus所說的-考慮導出整個對象(而不僅僅是函數),否則請使用bind

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM