john.mill john.mill - 4 months ago 6
Node.js Question

How to keep users array updated with user

Sorry, wasn't sure what exactly to search for as I'm sure this has been answered before but here goes. I have a webchat server using nodejs, I made a player class, but if I push the player class to the players array that contains all the users and update the player class such as player.id, the changes do not appear in the players array. How can I solve this?

var User = require('./User.js');



var wsID = 1; // should be random just for this example

var USERS = {};

USERS[wsID] = {
socket: "",
clientDetails: {
username: "",
isGuest: ""
}
}
user = new User();
user.setUsername("test");
USERS[wsID].username = user.getUsername; // works perfectly
user.setUsername("updatedit"); // fails to update array
console.log(USERS[wsID].username); // returns test and not updatedit...


class file:

var wsId,
socket,
username,
isGuest;

function User() {

}

User.prototype.getUsername = function(){
return this.username;
}

User.prototype.setUsername = function(name){
this.username = name;
}
module.exports = User;

Answer

You are missing the reference when you do this:

USERS[wsID].username = user.getUsername;

That's because you are cloning the current value of the property into another object. One way to solve this would be to change you code so you carry the instance "user" inside your "clientDetails" so it keeps updated:

user = new User();
user.setUsername("test");
USERS[wsID].clientDetails = user; // carry the entire instance
user.setUsername("updatedit");
console.log(USERS[wsID].clientDetails.username); // should return "updatedit"
Comments