To clarify my question, here are two examples in javascript-esque pseudocode. Here are the same examples but with a bit more code to contextualize them: http://pastebin.com/fRjW5qp6
See how I'm using conditionals to prevent sockets from triggering the important event logic after they've already triggered it once (e.g. I set socket.loginBuilt to true after the event listener has been triggered).
socket.on('login screen built', socketLoginScreenBuilt);
function socketLoginScreenBuilt() {
// See how I'm using this conditional to prevent sockets from triggering the important event logic after they've already triggered it once (since I set socket.loginBuilt to true in the logic)
if (!socket.loginBuilt) {
numberOfSocketsWithBuiltLoginScreens++;
socket.loginBuilt = true;
if (numberOfSocketsWithBuiltLoginScreens === io.sockets.sockets.length) {
app.emit('all login screens built')
}
}
}
socket.on('login credentials', socketLoginCredentials);
function socketLoginCredentials(credentials) {
if (readyForLoginCredentials) {
socket.username = credentials.username;
socket.password = credentials.password;
socket.emit('user stored data', socket.userData);
}
}
});
------------------- OR -------------------
Notice how I'm not using the conditionals I used above because I remove the listeners after the functions run for the first time. In that way I'll be certain that a socket won't trigger the important event logic multiple times.
socket.on('login screen built', socketLoginScreenBuilt);
function socketLoginScreenBuilt() {
// Notice how I'm not using a conditional here because I remove the 'login screen built' listener after this function is first ran. In that way I'll be certain that a socket won't trigger the important event logic multiple times
numberOfSocketsWithBuiltLoginScreens++;
socket.loginBuilt = true;
if (numberOfSocketsWithBuiltLoginScreens === io.sockets.sockets.length) {
app.emit('all login screens built')
}
socket.removeListener('login screen built', socketLoginScreenBuilt);
}
socket.on('login credentials', socketLoginCredentials);
function socketLoginCredentials(credentials) {
socket.username = credentials.username;
socket.password = credentials.password;
socket.emit('user stored data', socket.userData);
socket.removeListener('login credentials', socketLoginCredentials);
}
I want to clarify 2 things:
C/C++
tag but they make the point)So, in order to keep your code clean and, well, up-to-standards, you should use event-driven approach rather than global variables.
BTW in both cases you do use global variable
numberOfSocketsWithBuiltLoginScreens
.