Skip to content

Instantly share code, notes, and snippets.

@tphalp
Forked from ericflo/undo.js
Last active August 29, 2015 14:13
Show Gist options
  • Save tphalp/98011d4a0a8c1e20f3d6 to your computer and use it in GitHub Desktop.
Save tphalp/98011d4a0a8c1e20f3d6 to your computer and use it in GitHub Desktop.
var UndoMixin = {
getInitialState: function() {
return {
undo: []
};
},
handleUndo: function() {
if (this.state.undo.length === 0) {
return;
}
var nextUndo = _.initial(this.state.undo);
var nextState = _.last(this.state.undo);
nextState.undo = nextUndo;
this.setState(nextState);
},
handleUndoMixinKeyDown: function(ev) {
if (!(ev.which === 90 && (ev.ctrlKey || ev.altKey))) {
return;
}
this.handleUndo();
},
componentDidMount: function() {
document.addEventListener('keydown', this.handleUndoMixinKeyDown);
},
componentWillUnmount: function() {
document.removeEventListener('keydown', this.handleUndoMixinKeyDown);
},
setStateWithUndo: function(state, callback) {
var undo = this.state.undo.slice(0);
var undoItem = _.clone(this.state);
delete undoItem.undo;
undo.push(undoItem);
var nextState = _.extend({undo: undo}, state);
this.setState(nextState, callback);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment