amitdar
amitdar

Reputation: 927

keydown event not fired on ace editor

The ace editor prevent keydown events from being fired. I think it preventDefault.

How can i remove this prevention or bind to keydown event before the editor event is executed ?

Upvotes: 2

Views: 4032

Answers (2)

ewert
ewert

Reputation: 1835

I also wanted to be able to optionaly filter cursor key presses (and consume them in a popup instead of it). I was able to inject this functionality with the following code:

editor.keyBinding.origOnCommandKey = editor.keyBinding.onCommandKey;
editor.keyBinding.onCommandKey = function(e, hashId, keyCode) {
    if (...) { 
        this.origOnCommandKey(e, hashId, keyCode);
    }
}

keyCode 38 stands for cursor up, keyCode 40 for down and 13 for enter. If the original function is not called, Ace won't see this key presses. Unfortunately the return key is still consumed by Ace.

This may be prevented with a similar solution:

editor.keyBinding.origOnTextInput = editor.keyBinding.onTextInput;
editor.keyBinding.onTextInput = function(text) {
    if (...) {
        this.origOnTextInput(text);
    }
}

text is a newline in this case.

Upvotes: 3

a user
a user

Reputation: 24149

ace stops only the events it already handled, you can either use capturing event listener (editor.container.addEventListener("keydown", handler, true)) or use command handlers of ace

Update: to block ace commands only sometimes capturing event handler will work, but sometimes ace hashHandler is nicer than big switch over keycodes

HashHandler = require("ace/keyboard/hash_handler").HashHandler
var turn = 0
var h = new HashHandler([{
    bindKey: "Up",
    descr: "Block cursor movement smetimes",
    exec: function(ed){
        turn++
        if (turn % 2)
            return false // allow other ace commands to handle event
    }
}])
editor.keyBinding.addKeyboardHandler(h)
// editor.keyBinding.removeKeyboardHandler(h)

or more compact form

var h = new HashHandler()
h.bindKeys({"Up": function(ed){...}})

Upvotes: 5

Related Questions