Picture a NodeJS project structured like this:
./MASTER (root-folder)
- sockets-config.js // (M), instantiates Socket.IO and adds 'connect' listener
- ./node_modules
- ./projects
- ./ProjectA
- sockets-config.js // (A) binds project-a specific events.
- ./ProjectB
- sockets-config.js // (B) binds project-b specific events.
Now, let's say the NodeJS Socket.IO instance is created in (M) and attaches a "connect" event callback (and within that handler, attaches a few client.on("...whatever...", callback)
essentially used by all child projects), how do you extend / add more events to each clients within each sockets-config.js
project files (A & B)?
Can you pass the Socket.IO instance to those sockets-config.js
modules to attach an additional "connect" listener (if that's even necessary)? Will those resulting client references (in the on("connect", (client) => {...})
callbacks) be the same as the ones in the Master sockets-config.js
, so that they can have both project-specific & master events attached to them?
The only workaround I can think of is injecting the project-specific listeners into the (M) sockets-config.js
module within the "connect" listener, in the form of:
- Create a onConnectCallbacks array in (M) file.
- Load/Require all project-specific modules (A & B).
-
Each project module "appends" their onConnect callbacks to onConnectCallbacks, expecting a
client
as the single argument in the callback. -
In (M) file, instantiate Socket.IO and handle "connect" event.
- Inside the "connect" handler, add whichever events you need globally for all projects.
- Still inside the "connect" handler, iterate through onConnectCallbacks and invoke it with the currently connected client object as the 1st argument.
Example:onConnectCallbacks[i](client)
Is this method way too sloppy? I realize this exposes each project's events to eachother, so would "rooms" be better suited for a scenario like this (where 1 room = 1 project)?
via bigp
No comments:
Post a Comment