Last active
September 15, 2016 09:31
-
-
Save ericflo/9405239 to your computer and use it in GitHub Desktop.
Adds undo capabilities into your React.js component.
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 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