1

I'm making a chat in nodejs and i want to use the var user outside the socket.io scope but it keep giving me a undefined

here is my code that sets the user var

socket.on('bio', function(data) {
            for (var i = 0; i < data.length; i++) {
                    users[data[i].name] = {
                            avatar: data[i].avatar,
                            steamid: data[i].steamid,
                            name: data[i].name,
                            userid: data[i].id,
                            admin: data[i].admin
                    }
            }
    });

and here i try to use it but it says its undefined

textarea.addEventListener('keydown', function(event) {
        var self = this;

        if (event.which === 13 && event.shiftKey === false) {
            socket.emit('input', {
                timeStamp: moment().format("YYYY-MM-DDTHH:mm:ss"),
                name: chatName,
                userid: users[chatName].id,
                message: self.value
            });

            event.preventDefault();
        }
    });

it probably something stupid but I'm still in the learning phase :D

8
  • 1
    Have you created var users={}; in global scope? Commented Jul 21, 2015 at 12:51
  • yes i have just above the socket.on but when i console log it out in the key down function it gives this {} Commented Jul 21, 2015 at 13:02
  • And are you sure the socket call ran? Commented Jul 21, 2015 at 13:07
  • UPDATE - found the issue in the socket.emit i had to use id: users[chatName].id instead of userid: users[chatName].id Commented Jul 21, 2015 at 13:08
  • @HyperGainZ you can also just do users[data[i].name] = data; Commented Jul 21, 2015 at 13:18

2 Answers 2

1

hoisting problem in javascript.

example:

var v = "hello";
(function(){
  console.log(v);
  var v = "world";
})();

will be like this

var v = "hello";
(function(){
  var v; //declaration hoisting
  console.log(v);
  v = "world";
})();
Sign up to request clarification or add additional context in comments.

Comments

0

You need to set users in the global scope. At the top of your code just write:

var users = {};

That should get it working.

Just as some extra explanation, right now you are creating your users variable inside of that 'bio function', so anything that is not inside of that function doesn't know about the existance of your users variable. Declaring it in the global scope of your class, aka not inside of a function, lets all of your functions see it. This also means that once it gets assigned a value inside one function, it retains its value when used in other functions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.