ViewModel: 原本MVC中controller處理的邏輯移到ViewModel處理, 與View通常會做data binding.
用於data binding.
class ObservableObject<T> {
var value: T {
didSet {
self.valueChangedClosure?(self.value)
}
}
private var valueChangedClosure: ((T)-> (Void))?
init(value: T) {
self.value = value
}
func addObserver(isFireNow: Bool = true, _ valueChangedClosure: @escaping (T)-> (Void)) {
self.valueChangedClosure = valueChangedClosure
if(isFireNow == true) {
self.valueChangedClosure?(self.value)
}
}
func removeObserver() {
self.valueChangedClosure = nil
}
}
class MyViewModel: NSObject {
var titles = ObservableObject<[String]>(value: [])
var selectedIndex = ObservableObject<NSInteger>(value: 0)
}
private func initDataBinding() {
self.viewModel.titles.addObserver { [weak self] (titles) -> (Void) in
self?.collectionView.reloadData()
}
self.viewModel.selectedIndex.addObserver { [weak self] (titles) -> (Void) in
self?.collectionView.reloadData()
}
}