Last active
August 29, 2015 14:15
-
-
Save elpete/b6d5c32e1f92cb949819 to your computer and use it in GitHub Desktop.
Undo Redo Mixin for React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var UndoRedoMixin = { | |
componentWillMount: function() { | |
this.undoAction = false; | |
this.redoAction = false; | |
this.pastStates = []; | |
this.futureStates = []; | |
}, | |
componentDidUpdate: function(prevProps, prevState) { | |
if (this.undoAction) { | |
this.futureStates.push(prevState); | |
this.undoAction = false; | |
return; | |
} | |
this.pastStates.push(prevState); | |
if (!this.redoAction) { | |
this.futureStates = []; | |
} | |
this.redoAction = false; | |
}, | |
undo: function() { | |
var undoState = this.pastStates.pop(); | |
if (!this.pastStates.length) { | |
this.pastStates.push(undoState); | |
} | |
if (this.state !== undoState) { | |
this.undoAction = true; | |
this.setState(undoState); | |
} | |
}, | |
redo: function() { | |
var redoState = this.futureStates.pop(); | |
if (redoState) { | |
this.redoAction = true; | |
this.setState(redoState); | |
} | |
} | |
}; | |
module.exports = UndoRedoMixin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment