How to use the UndoManager to determine if document has unsaved changes

ensignos picture ensignos · Oct 29, 2013 · Viewed 16k times · Source

I'm quite new to the ACE editor and javascript in general however I have managed to achieve most of what I intended apart from the following:

I would like to enable or disable a 'save' button depending on whether there are outstanding modifications to the document and I have attempted to do this with 'change' event:

UndoManager.reset();

$('#save').addClass("disabled");

editor.on('change', function() {

        if (UndoManager.hasUndo()) {
            $('#save').removeClass("disabled");
        }
        else {
            $('#save').addClass("disabled");
        }

    });

On loading a document the 'disabled' class is removed immediately.

Many thanks in advance if anyone can show me how it should be done.

Answer

a user picture a user · Oct 31, 2013

Call editor.session.getUndoManager().reset() after loading the document and use isClean, markClean methods on undoManager.

var saveButton = document.getElementById("save")
var editor = ace.edit("editor")
// using input event instead of change since it's called with some timeout
editor.on("input", function() {
    saveButton.disabled = editor.session.getUndoManager().isClean()
});

saveButton.addEventListener("click", function() {
    editor.session.getUndoManager().markClean()
    saveButton.disabled = editor.session.getUndoManager().isClean()
})
<script src="http://ajaxorg.github.io/ace-builds/src/ace.js"></script>
<button id="save">save</button>
<div id="editor" style="height:200px"></div>