Last active
December 11, 2016 03:16
-
-
Save amberstar/180cd0e7796d281c5254335ca10e85c2 to your computer and use it in GitHub Desktop.
Trigger updates via. property observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// embed in the target (note props are read only) | |
protocol MySensor { | |
var name: String { get } | |
var age: Int { get } | |
} | |
// an example target that holds sensor | |
protocol MyView { | |
var sensor: MySensor { get set } | |
} | |
// dispatcher implements sensor | |
class Dispatcher: MySensor { | |
var name: String = "John" | |
var age: Int = 20 | |
} | |
class ConcreteView: MyView { | |
var sensor: MySensor { | |
didSet { | |
// this gets triggered when presenter updates | |
render(name: sensor.name, age: sensor.age) | |
} | |
} | |
init(sensor: MySensor) { | |
self.sensor = sensor | |
} | |
func render(name: String, age: Int) { | |
print("name: \(name), age: \(age)") | |
} | |
} | |
class Presenter { | |
var view: MyView | |
// source holds dispatcher with read write acess | |
var dispatcher: Dispatcher | |
init() { | |
self.dispatcher = Dispatcher() | |
self.view = ConcreteView(sensor: dispatcher) | |
} | |
func updateState(name: String, age: Int) { | |
// update state | |
dispatcher.name = name | |
dispatcher.age = age | |
// trigger update by reseting the sensor | |
view.sensor = dispatcher | |
} | |
} | |
var presenter = Presenter() | |
// we update the state triggering the sensor in the view to render | |
presenter.updateState(name: "Bob", age: 30) // name: Bob, age: 30 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment