Search code examples
javascriptjqueryevent-handlingsettimeouteventhandler

how to enable a disabled event handler with jquery


$("#messageArea").keydown(function(e) {                             
    if((e.which != 13) && (e.keyCode != 27)) {
        var $this = $(this);
        $this.off();
        socket.emit("imTyping");
        setTimeout(function() {
            $this.on();
        }, 2000);
    } 
});

I'm trying to create a chat app that lets one person know when the other person is typing. This event handler listens for any key press (except enter and esc) and emits the "imTyping" message to the server. After THIS event handler is called, I want to disable (so I don't send a million messages to the server) and then enable it again after 2 seconds. That isn't happening, once it disables it, it PERMANENTLY disables it.

Also I have other event handlers for the messageArea element, so I only want to turn of THIS handler, and not any of the others.


Solution

  • Extract into a named function and pass in the correct parameters when unbinding/rebinding

    $("#messageArea").keydown(typingKeydown);
    
    function typingKeydown(e) {                             
        if((e.which != 13) && (e.keyCode != 27)) {
            var $this = $(this);
            $this.off('keydown', typingKeydown);
            socket.emit("imTyping");
            setTimeout(function() {
                $this.on('keydown', typingKeydown);
            }, 2000);
        } 
    }