11import React , { Component , PropTypes } from 'react'
2+ import { withRouter } from 'react-router'
23import Modal from 'react-modal'
34import _ from 'lodash'
45import update from 'react-addons-update'
@@ -18,6 +19,7 @@ class EditProjectForm extends Component {
1819 this . saveFeatures = this . saveFeatures . bind ( this )
1920 this . onFeaturesSaveAttachedClick = this . onFeaturesSaveAttachedClick . bind ( this )
2021 this . submit = this . submit . bind ( this )
22+ this . onLeave = this . onLeave . bind ( this )
2123 }
2224
2325 componentWillMount ( ) {
@@ -37,11 +39,33 @@ class EditProjectForm extends Component {
3739 }
3840 this . setState ( {
3941 project : updatedProject ,
40- canSubmit : this . state . isFeaturesDirty ,
42+ isFeaturesDirty : false , // Since we just saved, features are not dirty anymore.
43+ canSubmit : false ,
4144 isSaving : false
4245 } )
4346 }
4447
48+ componentDidMount ( ) {
49+ this . props . router . setRouteLeaveHook ( this . props . route , this . onLeave )
50+ window . addEventListener ( 'beforeunload' , this . onLeave )
51+ }
52+
53+ componentWillUnmount ( ) {
54+ window . removeEventListener ( 'beforeunload' , this . onLeave )
55+ }
56+
57+ // Notify user if they navigate away while the form is modified.
58+ onLeave ( e ) {
59+ if ( this . isChanged ( ) ) {
60+ return e . returnValue = 'You have unsaved changes. Are you sure you want to leave?'
61+ }
62+ }
63+
64+ isChanged ( ) {
65+ // We check if this.refs.form exists because this may be called before the
66+ // first render, in which case it will be undefined.
67+ return ( this . refs . form && this . refs . form . isChanged ( ) ) || this . state . isFeaturesDirty
68+ }
4569
4670 enableButton ( ) {
4771 this . setState ( { canSubmit : true } )
@@ -102,7 +126,7 @@ class EditProjectForm extends Component {
102126 />
103127 < div className = "section-footer section-footer-spec" >
104128 < button className = "tc-btn tc-btn-primary tc-btn-md"
105- type = "submit" disabled = { ! this . state . canSubmit || this . state . isSaving }
129+ type = "submit" disabled = { ! this . isChanged ( ) || this . state . isSaving }
106130 > Save Changes</ button >
107131 </ div >
108132 </ div >
@@ -146,4 +170,4 @@ EditProjectForm.propTypes = {
146170 submitHandler : PropTypes . func . isRequired
147171}
148172
149- export default EditProjectForm
173+ export default withRouter ( EditProjectForm )
0 commit comments