I'm trying to find the right strategy to access a existing object from within my events handler, and wonder if the bypass I propose here after is a good option or not.
In following sample, I have a class to built a simple TCPServer. After server creation time, when a new tcpclient arrives, within "ConnectAction" function I need to access "devName" variable to find which server instance is concerned. As a result "DevName" cannot be global and needs to be specific to current instantiation of my TCPServer object.
------ Extract from my code --------
// TCPserver Object Class
TcpServer = function (devName, port) {
// event handler executed each time a new TCP client connect to the server
ConnectAction = function (socket) {
// for ech new client we create a new device and store it within server object
device = new TCPClient (devName, socket);
};
this.server = net.createServer(ConnectAction);
this.server.listen(port);
return this;
}
Server1 = new TcpServer ("My First Server", 8080):
Server2 = new TcpServer ("My Second Server", 8081):
In other script languages that I used in the past, it was possible to add an extra argument to event handlers. But in NODE.JS something like server=net.createServer(ConnectAction SomeExtraHandler); does not work.
The only bypass I find is to leverage arguments passed at object construction time. When the event handler code is embedded within the object border as in this example; then while even handlers are called outside of TCPserver object context "this not defined", handlers can still leverage parameters that where passed at object creation time. In this case "devName".
My question: is my bypass safe ? is there a better approach to solve this issue ? The full code of my sample is available at: http://www.fridu.org/download/private/TcpServer.js
If anyone has a better strategy, I would be more than happy to learn about it. In my real application, I should have ten or so differences server instances, with few hundred of clients connected to each of them. Which raise a second question, will my object coding approach in node.js support the load ?