0

I'm working on the following Node.js webapp, with handlebars and express for templating and routing. But a problem arises in the app.get('/', function(){ ... }) block.

The problem is that when it runs, it says it Cannot read property 'getData' of undefined at Object.<anonymous> (C:\Users\natha\Documents\GitHub\HAS\webUI\app.js:19:23)

var port     = 3000,
fs       = require('fs'),
exec     = require('child_process'),
express  = require("express"),
exphbs   = require("express3-handlebars"),
app      = express(),
Database = require('./db/Database.js'),
db       = new Database().selectDB('lights')
hbs      = exphbs.create({ defaultLayout: 'main'});


app.engine('handlebars', hbs.engine);
app.set('view engine','handlebars');
var io = require('socket.io').listen(app.listen(port))
app.enable('view cache');
app.use(express.static(__dirname + '/public'));

app.get('/',function(request, response){
    var data = this.db.getData();
    response.render('home', {
        helpers: {
           client: data.clients
        }
    });
});

io.sockets.on('connection', function (socket) {
    updateClients();



    socket.on('news', function(data, error){
        console.log(this.db);
    }.bind(this));
    socket.on('disconnect', function(){
        updateClients();
        console.log('hi');
    });

}.bind(this));

var updateClients = function(){
    var clients = [];
    io.sockets.clients().forEach(function(data){
        clients.push(data.id);
    });

    io.sockets.emit('news', { 
        users: clients
    });
}

I'm 100% sure it's not a asynchronous function problem, because when the socket.on('news', ....) runs which is triggered by a client far after the DB has initialized, it successfully prints the database info including the data..

This has to be a scope issue but I can't seem to fix it.

2
  • Maybe you mean db instead of this.db? Commented Sep 15, 2015 at 19:09
  • Apparently I did something stupid... I had to call the setDB after initializing the new Database() .. Now that I think about it, it makes sense. thanks anyway :) Commented Sep 15, 2015 at 19:44

1 Answer 1

1

Just remove this, db is just a variable, so it should be db.getData()

Sign up to request clarification or add additional context in comments.

2 Comments

Apparently I did something stupid... I had to call the setDB after initializing the new Database() .. Now that I think about it, it makes sense. thanks anyway :)
@NathanPrins Happens! The one thing that's tricky about JavaScript is keeping track of what this is at any given moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.