Retrieve the ACE Editor Instance from an HTML Element

HTML Javascript
2017-09-25 18:42 (7 years ago) ytyng

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);
});
Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011