Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. //MODEL-VIEW-PRESENTER
  2.  
  3. protocol EventHandler {
  4. func didTapButton()
  5. }
  6.  
  7. protocol ViewProtocol: AnyObject {
  8. var state: String {get set}
  9. }
  10.  
  11. class Presenter: EventHandler {
  12.  
  13. weak var view: ViewProtocol?
  14.  
  15. func didTapButton() {
  16. view?.state = "Hello"
  17. }
  18. }
  19.  
  20. class View: ViewProtocol {
  21.  
  22. let eventHandler: EventHandler
  23.  
  24. init(eventHandler: EventHandler) {
  25. self.eventHandler = eventHandler
  26. }
  27.  
  28. private func handleButtonTap() {
  29. eventHandler.didTapButton()
  30. }
  31.  
  32. var state: String = "" {
  33. didSet {
  34. updateViews()
  35. }
  36. }
  37.  
  38. private func updateViews() {
  39. print(state)
  40. }
  41. }
  42.  
  43. //MODEL-VIEW-VIEWMODEL
  44.  
  45. protocol ViewModelProtocol: AnyObject {
  46. func didTapButton()
  47.  
  48. var state: String {get set}
  49.  
  50. var stateWasChanged: (()->Void)? {get set}
  51. }
  52.  
  53. class ViewModel: ViewModelProtocol {
  54. func didTapButton() {
  55. state = "Hello"
  56. }
  57.  
  58. var state: String = "" {
  59. didSet {
  60. stateWasChanged?()
  61. }
  62. }
  63.  
  64. var stateWasChanged: (() -> Void)?
  65. }
  66.  
  67. class View {
  68.  
  69. let viewModel: ViewModelProtocol
  70.  
  71. init(viewModel: ViewModelProtocol) {
  72. self.viewModel = viewModel
  73.  
  74. viewModel.stateWasChanged = { [weak self] in
  75. self?.updateViews()
  76. }
  77. }
  78.  
  79. private func handleButtonTap() {
  80. viewModel.didTapButton()
  81. }
  82.  
  83. private func updateViews() {
  84. print(viewModel.state)
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement