2012-05-30 43 views
1

嗨,大家好我有一個應用程序佈局小問題。我正在像這樣設置我的控制器。NodeJS應用程序佈局和變量傳遞

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變量沒有顯示在其他實例方法中。這是我有遺漏的原因嗎?謝謝你的幫助。

在過去,我把我的控制器設置爲這樣。

module.exports = function(app) { 

    var controller = { 

      //app is defined 
      res.render('index', { 
       title: "Index" 
      }); 
     } 
    }; 

    return controller; 
}; 

但我更喜歡這個其他模式,我更加好奇,爲什麼它不起作用。

+0

你在'require()'之後如何使用'Application'? –

+0

更新的路線文件 –

回答

2

嘗試改變這些行:

app.get('/', Application.index); 
app.get('/blah', Application.blah); 

到:

app.get('/', Application.index.bind(Application)); 
app.get('/blah', Application.blah.bind(Application)); 

您的路線不被你的Application實例的上下文中調用,否則。

+0

啊我明白了。這就說得通了。我並不太熟悉綁定或我將如何使用它(至少在客戶端),但它現在更有意義。只是想知道..爲什麼它在第二種情況下工作?我猜我仍然無法將對象之外的方法拆分。 –

+0

沒關係我看。應用程序變量在所有這些函數的範圍內。所以,如果我在modules.export函數中包裝實例方法定義,它將工作(沒有綁定) –