【问题标题】:View Model composition breaks mvvm structure查看模型组合打破了 mvvm 结构
【发布时间】:2019-05-16 08:08:29
【问题描述】:

在 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()
     }

}




【问题讨论】:

    标签: swift mvvm


    【解决方案1】:

    我对此的解决方案是将视图模型作为视图层中的协议进行访问。虽然这增加了很多样板只是为了强制执行 mvvm。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-29
      • 2011-01-11
      • 2010-11-17
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多