Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8713029
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T05:14:40+00:00 2026-06-13T05:14:40+00:00

I believe this is some scope/variable access issue but I am not sure about

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T05:14:41+00:00Added an answer on June 13, 2026 at 5:14 am

    I think your code is still not the one that generated that output (i.e. 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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I believe this questions has been asked in some or the other way but
I have seen some code like this (not on consecutive lines, but in the
I am baffled with this questions. I want to believe that through some Javascript
I believe this is a fairly simple question but it is something I am
I believe this question applies to any of the For Html helpers, but my
I believe this to be related partially to short-circuiting logic, but I couldn't find
I believe this is possible but I haven't done it before. I need to
I believe this code may require more effort to comprehend than average, so I'm
I believe this question might have been previously attempted in 2006 on a different
I believe this question applies equally well to C# as to Java, because both

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.