1

I'm using Hapi.js for a project and a config variable that I'm passing to my handler is coming up as undefined when I call my route. What am I doing wrong?

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;
}

controllers/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;
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
minustime
  • 13
  • 4

1 Answers1

4

The issue is with the ownership of this. The value of this within any given function call is determined by how the function is called not where the function is defined. In your case above this was referring to the global this object.

You can read more on that here: What does "this" mean?

In short the solution to the problem is to change routes.js to the following:

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;
}

I've tested this and it works as expected. On a side note, you're missing out on a lot of hapi functionality by structuring your code in this way, I generally use plugins to register routes instead of requiring all routes as modules and using server.route().

See this project, feel free to open an issue if you have further questions on this: https://github.com/johnbrett/hapi-level-sample

Community
  • 1
  • 1
John
  • 837
  • 7
  • 14
  • Thanks for the answer John! this makes sense. I'm loading my handlers dynamically, I trimmed down the code just for this example. Could I have used the internals variable inside the home controller to hold my config variable? I'd really like to learn how to use Hapi properly but I haven't come across a kitchen sink type project that showcases Hapi's best practices. Are there more projects similarly to yours that I should look at? – minustime Nov 03 '14 at 16:22
  • There's a few: https://github.com/smaxwellstewart/hapi-dash https://github.com/jedireza/frame https://github.com/poeticninja/hapi-ninja And a more complicated version where you use the Hapi CLI to install: https://github.com/hueniverse/postmile – John Dec 22 '14 at 14:56