简体   繁体   中英

How to pass a variable to a predefined callback function in node.js

Using node.js, socket.io is calling onRegister() to check the mongoDB for a user. But the DB callback function is predefined, how can I add 'this' (ioHandle) to the callback parameters?

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

The error: ioHandle isn't being passed

TypeError: Cannot call method 'emit' of undefined

You don't need to add ioHandle to the findOne callback function, ioHandle will be in scope for that function through normal JavaScript closure mechanics:

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
            //...

You might want to spend a bit of time on the MDN closures page .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM