如何将变量传递给node.js中的预定义回调函数

时间:2013-09-01 04:58:06

标签: javascript node.js mongodb socket.io

使用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

1 个答案:

答案 0 :(得分:0)

您无需向ioHandle回调函数添加findOneioHandle将通过常规JavaScript闭包机制在该函数的范围内:

function onRegister(data) {
    // ioHandle will be visible to everything inside this function,
    // that includes the callback and nested callback below.
    var ioHandle = this;
    //...

    Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db) {
        //...
        collection.findOne({name : name}, function(err, doc) {
            // Use ioHandle as normal in here
            //...

您可能希望在MDN closures page上花一点时间。