使用 node.js,socket.io 正在调用 onRegister() 来检查用户的 mongoDB。但是数据库回调函数是预定义的,如何在回调参数中添加'this'(ioHandle)?
function onRegister(data) {
var name,pass,room;
name = data.name;
pass = data.pass;
ioHandle = this;
Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db, ioHandle) { // wrong
if(err) throw err;
var collection = db.collection('users');
// does user exist
collection.findOne({name : name}, function(err, doc, ioHandle) { // wrong
if(err) throw err;
if(doc) {
log("User already exists");
ioHandle.emit(NGC_REGISTER_RESULT, {NGC_REJECT:"User already Exists"}); // ioHandle undefined
} else {
// create new user
log("User not found");
ioHandle.emit(NGC_REGISTER_RESULT, NGC_ACCEPT); // ioHandle undefined
}
db.close();
});
});
}
错误: ioHandle 没有被传递
TypeError: Cannot call method 'emit' of undefined