2016-10-21 5 views
1

、と私MobXストアでの2つの観測:MobXの観測対象をクローンする方法はありますか? (変更の保存編集)私は、フォームをシンプルに反応している

個人情報の形式は、(ctorの中で)ロードされている
@observable personalInfo = { 
     email: '', 
     gender: 1, 
     birthDate: null, 
     location: '' 
    }; 
@observable personalInfoInEdit = null; 

私は上のメソッドを呼び出しています、私のstore:

reset_PersonalInfoInEdit() { 
     this.personalInfoInEdit = observable(this.personalInfo); 
} 

「編集中の」オブジェクトをリセットするだけで元のデータのデータで埋められます。ユーザーが「変更を保存」を押すと、「編集中の」オブジェクトがオリジナルにコピーされます。

observable()を別のobservableで呼び出しても有効ですか?これに副作用はありますか?

もしそうでなければ、この「編集中」のシナリオを優雅に扱うためのデザインパターンがありますか?

+0

私の知る限り、これで結構です。しかし確かめるために、cc @mweststrate –

+0

できませんか?this.personalInfoInEdit = this.personalInfo –

答えて

5

好ましいパターンは、mobx-utilscreateViewModelユーティリティー機能を使用することです。だから、あなたはどうなる:

import { createViewModel } from 'mobx-utils' 

reset_PersonalInfoInEdit() { 
    this.personalInfoInEdit = createViewModel(this.personalInfo); 
} 

これは、簡単に元のデータにリセットするか、元のモデルに提出できるようにするビューモデルにいくつかのユーティリティ機能を有するという利点もあります。

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 
+0

うわー、私はこれが存在しているのか分かりませんでした。私はそれがMobxの主要なドキュメントにあったと思います。 – rclai

関連する問題