Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class SimpleCommand(
- private val action: () -> Unit,
- private val isEnabledPredicate: () -> Boolean = { true },
- private val isVisiblePredicate: () -> Boolean = { true }
- ) : Command {
- private val boundComponents = LinkedHashSet<Component>(1)
- private val listener = object : Property.ValueChangeListener, Container.ItemSetChangeListener, Button.ClickListener {
- override fun valueChange(event: Property.ValueChangeEvent?) = refresh()
- override fun containerItemSetChange(event: Container.ItemSetChangeEvent?) = refresh()
- override fun buttonClick(event: Button.ClickEvent?) = execute()
- }
- override fun execute() = when {
- isEnabled -> action()
- else -> throw IllegalStateException("Command is disabled")
- }
- override val isEnabled: Boolean
- get() = isEnabledPredicate()
- override val isVisible: Boolean
- get() = isVisiblePredicate()
- private fun bindComponent(component: Component) {
- if (boundComponents.add(component)) {
- refreshComponent(component)
- }
- }
- private fun unbindComponent(component: Component) {
- if (boundComponents.remove(component)) {
- component.isEnabled = true
- component.isVisible = true
- }
- }
- private fun refreshComponent(component: Component) {
- component.isEnabled = isEnabled
- component.isVisible = isVisible
- }
- private fun refresh() {
- for (component in boundComponents) {
- refreshComponent(component)
- }
- }
- override fun bindNotifier(notifier: Property.ValueChangeNotifier) = notifier.addValueChangeListener(listener)
- override fun unbindNotifier(notifier: Property.ValueChangeNotifier) = notifier.removeValueChangeListener(listener)
- override fun bindNotifier(notifier: Container.ItemSetChangeNotifier) = notifier.addItemSetChangeListener(listener)
- override fun unbindNotifier(notifier: Container.ItemSetChangeNotifier) = notifier.removeItemSetChangeListener(listener)
- override fun bindButton(button: Button) {
- button.addClickListener(listener)
- bindComponent(button)
- }
- override fun unbindButton(button: Button) {
- button.removeClickListener(listener)
- unbindComponent(button)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement