简体   繁体   中英

Object/Method/Variabe access in node.js/socket.io

I believe this is some scope/variable access issue but I am not sure about it so I am going to tell you the whole context.

The idea is to have a node.js-"application" which lets you enter a number in a HTML frontend which is sent to the server via socket.io and then saved to mongodb with mongoose. And then, in return to get the number from the database and do something with it in the client-side script.

A real-life example would be that you are able to enter the mileage of your car/whatever on the clientside, then fire a socket.io event that transfers this information to the node.js server and save it there to monogodb using mongoose. That works. Now say I also want to be able to keep and save some preferences.
I have a Preferences object that keeps the variable numDigits and some methods/functions.
Saving numDigits to the server works, querying the entry from the server works.
However, saving the number into Preferences.numDigits does not.

client.js

//init.js
//var Preferences;

var Preferences = {
    numDigits: 'default',
    parse: function(){
        this.numDigits = parseInt($('#preferences > #num-digits').val());
    },
    get: function(){
        socket.emit('req-preferences', function(responseData) {
            this.numDigits = responseData.numDigits;
            console.log('#1: ' + this.numDigits);
        });
        console.log('#1: ' + this.numDigits);
        // 2 different outputs (scopes?) here

    },
    save: function(){
        socket.emit('save-preferences', this);
    }
}

var UI = {
    numDigits: Preferences.numDigits,
    build: function() {
        Preferences.get();
        console.log(Preferences.numDigits);
        for (i=0; i<Preferences.numDigits;i++) {
            $('#input-km').append('<input type="text"></input>');
        }   
    }
}

$(document).ready(function() {

    socket = io.connect('http://127.0.0.1:8080');


    function print(data) {
        console.log(data);
        if (data.length == 0) {
            $('#results').html('no entries!');
        } else {
            for (i = 0; i < data.length; i++) {
                $('#results').append(data[i].date + ' - ' + data[i].km + '<br />');
            }   
        }
    }

    socket.on('res-entries', function(entries){
        print(entries);
    });

    $('#submit').click(function() {
        var kmStand = $('#km').val();
        socket.emit('submit', kmStand, function(){
        });
    });

    $('#req-entries').click(function(){
        socket.emit('req-entries', function() {
        });
    });


    $('#remove-all').click(function() {
        socket.emit('remove-all', function() {
            console.log('remove all');
        });
    });

    $('#save-preferences').click(function() {
        Preferences.parse();
        Preferences.save();
    });

    //Preferences.get();
    UI.build();
});

server.js

var http = require('http');
var connect = require('connect');
var io = require('socket.io');
var mongoose = require('mongoose');

var server = http.createServer(connect()
    .use(connect.static(__dirname))).listen(8080);

var socket = io.listen(server);
socket.set('log level', 2);

var db = mongoose.createConnection('localhost', 'mileagedb');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {

    var entrySchema = new mongoose.Schema({
        km: String,
        date: {
            type:Date, 
            default:Date.now
        }
    });

    var preferencesSchema = new mongoose.Schema({
        numDigits: Number,
        objId: Number
    });

    var Preferences = db.model('Preferences', preferencesSchema);

    var Entry = db.model('Entry', entrySchema);

    socket.sockets.on('connection', function(socket){ 

        socket.on('submit', function(kmStand){
            var eintrag = new Entry({
                km: kmStand,
            });

            eintrag.save(function(err) {
                if (err) {
                    console.log('error while saving');
                } else {
                    console.log('saved');
                }
            });

            Entry.find(function(err, entries) {
                console.log('all entries:');
                console.log(entries);
            });
        });

        socket.on('req-entries', function() {
            Entry.find(function(err, entries) {
                socket.emit('res-entries', entries);
            });
        });

        socket.on('remove-all', function() {
            Entry.find().remove();
            Preferences.find().remove();
        });

        socket.on('save-preferences', function(prefObj) {

            Preferences.update(Preferences.findOne(), {$set: { numDigits: prefObj.numDigits }}, { upsert: true }, function(err){
                if (err) {
                    console.log('error saving');
                }
            });

            Preferences.find(function(err, prefs) {
                console.log('all preferences:');
                console.log(prefs);
            });
        });

        socket.on('req-preferences', function(fn) {
            Preferences.findOne(function(err, prefs) {
                fn(prefs);
            })
        });

    });
});



/* maybe:
socket.on('get-entries'), function(requestSpecification) {
            ...
        }*/

The console output on the client side is:

(on body load, UI.build() fires)
#2: default (line 14)
#1: 5 (line 12)

>Preferences.get();
#2: default (line 14)
<-undefined
#1: 5 (line 12)

>Preferences.numDigits
"default"

the for-loop in UI.build() also doesnt fire so I take the value it has there is "default" too. As mentioned before, I am pretty sure it is a variable/scope issue somewhere in Preferences.get(); but I just cant understand the problem on my own. It would be too nice if someone of you could help me out on that.

Thanks a lot in advance!

edit: pasted wrong code

I think your code is still not the one that generated that output (ie both line 12 and 14 in the code contain #1. Anyways, that's probably not the issue.

OK, firstly, I though that the second parameter to "emit" should be the data to send, and only the third should be the callback function. But perhaps this does work.

Then the scoping issue. Always be careful with what "this" points to in closures (=callback functions). Best solution would be:

get: function(){
    var that = this;
    socket.emit('req-preferences', function(responseData) {
        that.numDigits = responseData.numDigits;
        console.log('#1: ' + that.numDigits);
    });
    console.log('#1: ' + that.numDigits);
    // 2 different outputs (scopes?) here

},

Myself, I always have the first line of any member function be "var that = this", and then only refer to "that" throughout the function. If you really want to learn why, check the description . Also, using "use strict" throughout your code can help prevent these kinds of problems.

I haven't tried it, but I would think this should help.

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