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.
只需删除this
,db只是一个变量,所以它应该是db.getData()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.