Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 837
ensignos Avatar asked Oct 29 '13 22:10

ensignos


2 Answers

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>
like image 111
a user Avatar answered Nov 12 '22 20:11

a user


Your solution has a disadvantage: after saving, you are not able to undo. Most modern editors allow undo after saving.

I suggest that you record down the original text and do a comparision whenever text changes. if text equals origin, disable save button.

like image 21
Tyler Liu Avatar answered Nov 12 '22 20:11

Tyler Liu