gpt4 book ai didi

javascript - 就效率和优雅而言,添加和删除事件监听器或使用全局/高级变量来控制发射器事件逻辑更好吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:15 24 4
gpt4 key购买 nike

为了澄清我的问题,这里有两个 Javascript 式伪代码的示例。以下是相同的示例,但使用了更多代码来将它们置于上下文中: 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 是事件驱动的。
  • 全局变量是 evil (有一个 C/C++ 标签,但它们很说明问题)

因此,为了保持代码整洁并且符合标准,您应该使用事件驱动方法而不是全局变量。

顺便说一句,在这两种情况下,您确实使用全局变量numberOfSocketsWithBuiltLoginScreens

关于javascript - 就效率和优雅而言,添加和删除事件监听器或使用全局/高级变量来控制发射器事件逻辑更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34601895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com