问题
I have a simple react form, and two observables in my MobX store:
@observable personalInfo = {
email: '',
gender: 1,
birthDate: null,
location: ''
};
@observable personalInfoInEdit = null;
When the form of the personal info is loaded (in the ctor) I am calling a method on my store:
reset_PersonalInfoInEdit() {
this.personalInfoInEdit = observable(this.personalInfo);
}
What it dose is simply reseting the "in edit" object, filling it with data from the original data. If the user press "save changes" the "in edit" object will be copied to the original.
Is calling observable() with another observable is valid? Any side effects to this? (it seems to work)
And if not, are there are design patterns to elegantly handle this scenario of "in edit" object.
回答1:
The preferred pattern would be to use createViewModel utility function from mobx-utils. So you would do:
import { createViewModel } from 'mobx-utils'
reset_PersonalInfoInEdit() {
this.personalInfoInEdit = createViewModel(this.personalInfo);
}
this has an added benefit of having some utility functions on the view model that allow you easily to reset to original data or submit them to original model:
class Todo {
\@observable title = "Test"
}
const model = new Todo()
const viewModel = createViewModel(model);
autorun(() => console.log(viewModel.model.title, ",", viewModel.title))
// prints "Test, Test"
model.title = "Get coffee"
// prints "Get coffee, Get coffee", viewModel just proxies to model
viewModel.title = "Get tea"
// prints "Get coffee, Get tea", viewModel's title is now dirty, and the local value will be printed
viewModel.submit()
// prints "Get tea, Get tea", changes submitted from the viewModel to the model, viewModel is proxying again
viewModel.title = "Get cookie"
// prints "Get tea, Get cookie" // viewModel has diverged again
viewModel.reset()
// prints "Get tea, Get tea", changes of the viewModel have been abandoned
来源:https://stackoverflow.com/questions/40185513/how-can-i-clone-a-mobx-observable-edit-save-changes