I'm building a server/client model with Node.JS and want to call a function of an already instantiated class by using a variable packet-ID and handle the incoming server-packets by different functions. Therefore I put the packet-ids as properties of the PacketMethods object and the function to call as the value of each packet-id-property. However in this example when ServerList() is called, it's not a member of the initiated Client Class and therefore this.socket is undefined.
How could I call the packet-handling functions so that they're a member of the Client?
function Client (...)
{
this.socket = new net.Socket();
...
}
Client.prototype.HandlePacket = function(blocks)
{
try {
var sPacket = new WRPacket(blocks);
var PacketMethods = {
4352 : this.ServerList
4351 : this.LoginResponse
}
if(PacketMethods.hasOwnProperty(sPacket._packetid))
PacketMethods[sPacket._packetid](sPacket);
else
console.log('Unhandled Packet: '+sPacket._packetid);
} catch(err) {
console.log("Error at Packet-Handler:\n"+err);
}
}
Client.prototype.ServerList = function(Packet)
{
console.log('Serverlist received ...');
...
this.socket.end();
}
Thank you!
You can bind the methods to your instance:
var PacketMethods = {
4352 : this.ServerList.bind(this),
4351 : this.LoginResponse.bind(this)
}
You could simply use the PacketMethods to store the names of your methods, then call them with the correct context:
var PacketMethods = {
4352 : 'ServerList'
4351 : 'LoginResponse'
};
if (PacketMethods.hasOwnProperty(sPacket._packetid)) {
var method = PacketMethods[sPacket._packetid];
this[method](sPacket);
}