2014-11-01 59 views
0

我正在使用Hapi.js作爲項目,並且我將傳遞給我的處理程序的配置變量將作爲未定義,當我呼叫我的路線時。我究竟做錯了什麼?Hapi在處理程序中顯示未定義的變量

server.js

var Hapi = require('hapi'); 
var server = new Hapi.Server('0.0.0.0', 8080); 

// passing this all the way to the handler 
var config = {'number': 1}; 

var routes = require('./routes')(config); 
server.route(routes); 

server.start(); 

routes.js

var Home = require('../controllers/home'); 

module.exports = function(config) { 
    var home = new Home(config); 
    var routes = [{ 
     method: 'GET', 
     path: '/', 
     handler: home.index 
    }]; 
    return routes; 
} 

控制器/ home.js

var Home = function(config) { 
    this.config = config; 
} 

Home.prototype.index = function(request, reply) { 

    // localhost:8080 
    // I expected this to output {'number':1} but it shows undefined 
    console.log(this.config); 

    reply(); 
} 

module.exports = Home; 

回答

3

的問題是與第e擁有this。任何給定函數調用中的this的值由調用函數的方式決定,而不是函數的定義位置。在你上面的案例中,this指的是全球this對象。

你可以閱讀更多的是在這裏:What does "this" mean?

總之解決問題的辦法是改變routes.js以下:

var Home = require('../controllers/home'); 

module.exports = function(config) { 
    var home = new Home(config); 
    var routes = [{ 
     method: 'GET', 
     path: '/', 
     handler: function(request, reply){ 
      home.index(request, reply); 
     } 
    }]; 
    return routes; 
} 

我測試過這一點,它的工作原理爲預期。在附註中,通過以這種方式構造代碼,您錯過了很多hapi功能,我通常使用插件來註冊路由,而不是將所有路由作爲模塊並使用server.route()

看到這個項目,覺得免費的,如果你對此還有疑問,打開一個問題:在回答約翰https://github.com/johnbrett/hapi-level-sample

+0

謝謝!這是有道理的。我正在動態加載我的處理程序,我只是爲了這個例子而修改了代碼。我可以使用家庭控制器內部的變量來保存我的配置變量嗎? 我真的很想學習如何正確使用Hapi,但我還沒有遇到過展示Hapi最佳實踐的廚房水槽類型項目。是否有更多類似於你的項目,我應該看看? – minustime 2014-11-03 16:22:50

+0

有幾個: https://github.com/smaxwellstewart/hapi-dash https://github.com/jedireza/frame https://github.com/poeticninja/hapi-ninja 還有一個更復雜的版本,您可以使用Hapi CLI進行安裝: https://github.com/hueniverse/postmile – John 2014-12-22 14:56:25