Retrieve the ACE Editor Instance from an HTML Element
HTMLJavascript
2017-09-25 09:42 (8 years ago)

I wanted to use the save shortcut key (Ctrl + S / Command + S) while using ACE in Django-ACE.
Django-ACE creates an editor instance like this in widget.js:
editor = ace.edit(div)
However, since it's a local variable within a function, you can't access it from outside the function.
In such cases, you can access it via div.env.editor.
When using ACE in Django Admin, you can write the reference access to the editor using jQuery like this:
$('div.django-ace-widget')[0].firstChild.env.editor
To bind the shortcut for Ctrl + S (Command + S), you can write it like this:
$('div.django-ace-widget')[0].firstChild.env.editor.commands.addCommand({
name: "save",
bindKey: {
win: "Ctrl-S",
mac: "Command-S"
},
exec: function(editor) {
alert('Save!');
}
});
If you want to include this in Django's Admin JS, you can write it like this:
// Admin ACE Save
$(function() {
setTimeout(function() {
var aces = $('div.django-ace-widget');
if (!aces.length) {
return;
}
var editor = aces[0].firstChild.env.editor;
if (!editor) {
return;
}
var continueButton = $('input[type="submit"][name="_continue"]');
if (!continueButton.length) {
return;
}
editor.commands.addCommand({
name: "save",
bindKey: {
win: "Ctrl-S",
mac: "Command-S"
},
exec: function(editor) {
continueButton.click();
}
});
}, 2000);
});
Please rate this article
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.