在mvvm中,视图永远无法访问模型。
我将“视图模型组成”定义为一个视图模型可能具有一对多子视图模型的概念
如果父视图模型需要更改其子视图模型中的1个模型,则如果该视图有权访问该视图模型,则其固有地有权更改子vm模型。
我可以使用哪种方法来强制执行“视图永不访问模型”规则?
Swift中的示例代码
class BigVm{
let accountVm: AccountViewModel
let anotherVm: AnotherSubviewViewModel
private func someEventHappened(){
//some logic that mutates accountVm's model based on state of anotherVm and vise versa
accountVm.mutateOrAccessModel()
}
}
class BigViewController: UIViewController{
let viewModel: BigVm
let subviewAccount: AccountView //has a viewModel of AccountViewModel
let anotherSubview: AnotherSubview //has a viewModel of AnotherSubviewViewModel
func viewDidLoad(){
super.viewDidLoad()
subviewAccount.vm = viewModel.accountVm
anotherSubview.vm = viewModel.anotherVm
//now what stops BigViewController to do the next lines
viewModel.subViewAccount.mutateOrAccessModel()
}
}
答案 0 :(得分:-1)
我对此的解决方案是在视图层中作为协议访问viewModels。尽管这增加了很多用于执行mvvm的样板。