MVVM架构的核心是View-Model,View-Model是一种特殊的Model,它代表了应用UI的各种状态.
它包含了描述各种UI管理的状态的属性.例如一个TextField中当前的text,一个button是否是enable状态.同时它也向外界提供当前View可以执行的action,例如button的点击和手势的触发.MVVM需要遵循以下规则
- View持有ViewModel,但是反过来不可以
- ViewModel持有Model,但是反过来不可以
- 这个模式最直接的好处如下:
- 轻量级的View --- 因为所有的UI逻辑都存在于ViewModel中,所以View会非常轻量级
- 测试 --- 可以再没有不依赖View的情况下运行程序,极大增强了可测试性
MVVM架构依赖于数据绑定,并且是双向的数据绑定,ViewModel的属性发生了变化要传递给UI,UI上用户输入了变化也要传递给ViewModel.
UIButton的rac_command属性跟RACCommand实例绑定后,可以控制UIButton的enable状态,同时,点击UIButton的时候执行该command(validSearchSignal传递YES的时候button可点击,传递NO的时候Button不可点击)
[[RACCommand alloc] initWithEnabled:validSearchSignal
signalBlock:^RACSignal *(id input) {
return [self executeSearchSignal];
}];
self.searchButton.rac_command = self.viewModel.executeSearch;
RACCommand的executing属性可以用来判断当前的command是否正在执行
not方法可以将RACSignal中传递的值取反
RACCommand的executionSignals属性会把每次command执行的时候创建的signal传出来(如果command绑定的button,并且点击button的时候需要做一些操作,可以用这个属性)
[self.viewModel.executeSearch.executionSignals
subscribeNext:^(id x) {
[self.searchTextField resignFirstResponder];
}];
- The ViewModel exposes properties that represent the UI state, it also exposes commands — and often methods — that represent UI actions. It’s responsible for managing changes to the UI state based on user interactions.
However, it’s not responsible for the actual business logic that executes because of these interactions. That is the job of the Model. - MVVM结构总结
1.model层提供服务和业务逻辑,在Flickr这个例子里,model层提供Flickr搜索照片的服务
- View-Model层代表了整个应用UI的各种状态,同时它也对用户交互和和来自Model层的事件进行回应(UI状态的改变).
- View层功能非常简单,它只提供View-Model层各种状态的展示和用户交互.