ArthurClemens/JavaScript-Undo-Manager

how to handle asyn commands?

Closed this issue · 3 comments

Hello, nice lib. I'm trying to add do/redo functionallity, the only issue I have is that some of my commands (do/redos) are async, so it turns into rare behavior when I click "ctrl+z" pretty fast, because the last undo call is not waiting for the firsts calls. Is there a way to handle this ?

thanks.

xeii commented

Try this

var isUndoing = false;

undoManager.setCallback(function(){
  isUndoing = false;
});

function whenUndoIsCalled () {
 isUndoing = true;
 undoManager.undo();
}

Then disable/enable your button/ctrl-z trigger with the isUndoing boolean.

EDIT: I had the same problem and for a second I thought that worked, might be I celebrated too early.

I'm going to assume your undo/redo operations take a callback that's called when they complete (successfully or not). You can then wrap the UndoManager like so:

var isUndoing = false;

function add(operations) {
    undoManager.add({
        undo: function() {
            isUndoing = true;
            operations.undo(function() {
                isUndoing = false;
            });
        }
        redo: function() {
            isUndoing = true;
            operations.redo(function() {
                isUndoing = false;
            });
        }
    });
}

function hasUndo() {
    return !isUndoing && undoManager.hasUndo();
}

function hasRedo() {
    return !isUndoing && undoManager.hasRedo();
}

@nonplus is that example complete? It seems like hasUndo and hasRedo are not used? Did anyone figure out how to do async correctly?