使用KeyUp在node.js中键入通知

Par*_*ars 1 javascript jquery node.js

我正在使用Node.js并制作聊天应用程序.

假设用户A正在与用户B聊天.在每个用户开始键入的所有聊天应用程序中,出现一个通知,其中显示"用户X正在键入...".

我有类似的"打字......"功能.使用这种方法:

$(document).on('keyup','form.chat input:text', function(e){
    var $id = $(this).attr('id'); // text id is the user id we are chating with.
    if ( $(this).val().trim().length > 0 )
        socket.emit("writingOn", $id );
    if ( $(this).val().trim().length === 0 )
        socket.emit("writingOff", $id );
});
Run Code Online (Sandbox Code Playgroud)

它运作良好.但问题是:
这是一个好方法吗?因为foreach keyUp客户端向服务器发送req

提前致谢.

Ber*_*rgi 6

这是一个好方法吗?

要在实时编辑应用程序中发送每个击键,是的.为了提供"正在打字"功能,没有.

您只需在用户开始键入时发送消息,并在他未键入一段预定时间时发送消息.对每次后续击键重置的超时使用超时.在您的情况下,您需要为他可以输入的每个字段收集一组超时.

var timeouts = {},
    time = 2000;
$(document).on('keyup','form.chat input:text', function(e){
    var id = this.id/*,
        isEmpty = /^\s*$/.test(this.value) */;
    if (id in timeouts) // if something is scheduled
        clearTimeout(timeouts[id]); // remove it
    else /* if (!isEmpty) */ // else this is the first stroke
        socket.emit("writingOn", id);
    // schedule sending the off-message, which will be canceled when another
    // keystroke happens
    timeouts[id] = setTimeout(function() {
        socket.emit("writingOff", id);
        delete timeouts[id];
    }, /* isEmpty ? 0 : */ time);
});
Run Code Online (Sandbox Code Playgroud)