在效率和优雅方面,添加和删除事件侦听器还是使用全局/高级variables来控制发射器事件逻辑更好?

为了澄清我的问题,下面是两个例子在javascript-esque伪代码。 这里是相同的例子,但有更多的代码来上下文化他们: http : //pastebin.com/fRjW5qp6

看看我是如何使用条件来防止套接字触发重要的事件逻辑后,他们已经触发过一次(例如,我已经设置了事件监听器触发后,socket.loginBuilt为true)。

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); } } }); 

– – – – – – – – – – 要么 – – – – – – – – – –

注意我没有使用上面使用的条件,因为我在第一次运行函数之后删除了监听器。 这样我就可以确定一个套接字不会多次触发重要的事件逻辑。

 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); } 

我想澄清两件事情:

  • Node.js是事件驱动的。
  • 全局variables是邪恶的 (有一个C/C++标签,但他们表明)

因此,为了保持代码清洁,并且遵循标准,您应该使用事件驱动方法而不是全局variables。

顺便说一句,你使用全局variablesnumberOfSocketsWithBuiltLoginScreens