So, I'm pretty new to JavaScript, and while I know the little tricks to do things like this in Java the same tricks don't really apply here, or at least I can't really figure out how to use them, so I'm currently using two objects in the form of collections:
var ConnectedClients_socket = {};
var ConnectedClients_networkId = {};
The hold a key/value pair to link a networkID to a client and then a duplicated object that uses the socket as a key. Any optimizations would be great, I'll be grabbing the client by the socket and ID a lot throughout the application.
On to the problem:
Upon disconnection I need to remove the client instance from the ConnectedClients_networkId object. From my understanding this is done using the delete keyword.
Here's the code I'm currently trying to use for this:
console.log('socket disconnected');
delete Client.ConnectedClients_networkId[Client.ConnectedClients_socket[socket].getNetworkId()];
delete Client.ConnectedClients_socket.socket;
However this is giving me the following error:
TypeError: Cannot call method 'getNetworkId' of undefined
which shows that
Client.ConnectedClients_socket[socket]
is returning undefined, while Client.ConnectedClients_socket.socket is being removed successfully a line later. I've looked up a few different pages on getting a value from a key in JavaScript, and I don't see what I'm doing wrong.
Here's the constructor for a client:
var Client = function(networkId, socket, ...) {
this.networkId = networkId;
this.socket = socket;
...
ConnectedClients_socket.socket = this;
ConnectedClients_networkId.networkId = this;
}
-
Nice job describing your problem; +1.Scimonster– Scimonster2015年02月06日 09:10:29 +00:00Commented Feb 6, 2015 at 9:10
-
Indeed, very clean description. +1Bitwise Creative– Bitwise Creative2015年02月06日 09:10:59 +00:00Commented Feb 6, 2015 at 9:10
-
Isnt the line Client.ConnectedClients_socket[socket].getNetworkId() should be Client.ConnectedClients_socket.socket.getNetworkId() ?Deshan– Deshan2015年02月06日 09:12:26 +00:00Commented Feb 6, 2015 at 9:12
2 Answers 2
Quotes?
Client.ConnectedClients_socket['socket']
However, there is no need for this notation here.
Client.ConnectedClients_socket.socket
Is fine.
Bracket notation can be used for accessing members with special characters or by variable value.
Client.ConnectedClients_socket['someArr[]']
or
var x = 'socket';
Client.ConnectedClients_socket[x]
Comments
You need to use dot notation there.
delete Client.ConnectedClients_networkId[Client.ConnectedClients_socket.socket.getNetworkId()];
Bracket notation will parse it as JavaScript, so it's useful for dynamically getting a property.