Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data Binding in MVVM #103

Closed
Youngminah opened this issue Dec 27, 2021 · 0 comments
Closed

Data Binding in MVVM #103

Youngminah opened this issue Dec 27, 2021 · 0 comments
Labels

Comments

@Youngminah
Copy link
Owner

MVVM

image

  • View는 View Model을 가지고, View Model은 Model을 가집니다.
  • View Model은 입출력을 처리하고 UI가 요구하는 비지니스 로직을 처리하는 역할만 가집니다.
  • View Model은 UI를 수정할 수 없습니다.

비지니스 로직 : 유저 눈에는 보이지 않지만, 유저가 바라는 결과물을 올바르게 도출할 수 있도록 짜여진 코드


Observable을 통한 데이터 바인딩

class Observable<T> {

    var value: T { didSet { listener?(value) } }

    private var listener: ((T) -> Void)?

    init(_ value: T) {
        self.value = value
    }

    func bind(_ closure: @escaping (T) -> Void) {
        closure(value)
        listener = closure
    }
}

ViewModel

class ViewModel  {
   var username = Observable("고래밥")
   var password = Observable("")
}

ViewController

class ViewController  {

   override func viewDidLoad() {
      viewmodel.username.bind { text in
         self.mainView.usernameTextField.text = text
      }

      viewmodel.password.bind { text in
         self.mainView.passwordTextField.text = text
      }
   }

   @objc func passwordTextFieldDidChange(_ textfield: UITextField) {
      viewmodel.password.value = textfield.text ?? ""
   }

   @objc func usernameTextFieldDidChange(_ textfield: UITextField) {
      viewmodel.username.value = textfield.text ?? ""
   }
}

참고자료

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant