问题
I recently had a textarea on my jsp page
For it, I had my own shortcuts on the keyboard
Then, I implemented the ace editor, and all my old keybindings didn't work then
Then i searched for a while, and found this code:
//I did this before, to add the ace editor
var editor = ace.edit("fileInfo");
var JavaScriptMode = ace.require("ace/mode/javascript").Mode;
editor.session.setMode(new JavaScriptMode());
//Then I found this for the keyBindings
delete editor.keyBinding;
The last line, disables all the keyBindings from the ace editor, and my own keyBindings came to work... All worked fine, but then, I searched a lot about the ace editor, and found one interesting option, and thet is the one keyBinding, that I love to use, and that is the DELETE ROW keybinding Ctrl + D
and I want now to get it back, but only it, not the others, and ofc my old keyBindings should also work...
The code for my old keyBindings looks like this:
document.addEventListener("keydown", function(e) {
// Ctrl + S = SAVE
if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
e.preventDefault();
e.stopPropagation();
if($scope.mode!='BROWSE')
{
$('#saveBtn').trigger("click");
}
}
}, false);
Can u help me?
回答1:
delete editor.keyBinding;
is not a good solution, it will produce error messages in console
Uncaught TypeError: Cannot read property 'ctrl-d' of undefined at CommandManager.handleKeyboard (ace.js:10830) at KeyBinding.$callKeyboardHandlers (ace.js:4081) at KeyBinding.onCommandKey (ace.js:4113) at Editor.onCommandKey (ace.js:12424) at normalizeCommandKeys (ace.js:1648) at HTMLTextAreaElement. (ace.js:1667)
Option 1: delete all bindings and redefine the one we need.
//safely delete all bindings
editor.keyBinding.$defaultHandler.commandKeyBinding = {}
//bind the wanted command
editor.commands.addCommand({
name: "removeline",
bindKey: { win: "Ctrl-D", mac: "Command-D" },
exec: function(editor) { editor.removeLines(); },
scrollIntoView: "cursor",
multiSelectAction: "forEachLine"
});
now that you have the command defined, you can call it from your own code if needed:
editor.execCommand("removeline")
Option 2: actually looping through the bindings.
using for (key in obj)
to loop through the key bindings and deleting keys that are not equal to ctrl-d
and command-d
:
for (key in editor.keyBinding.$defaultHandler.commandKeyBinding) {
if (key !== "ctrl-d" && key !== "command-d")
delete editor.keyBinding.$defaultHandler.commandKeyBinding[key]
}
来源:https://stackoverflow.com/questions/42410689/ace-editor-how-to-remove-all-keybindings-but-one