Advertisement
MadMax1028

SimpleCommand

Oct 9th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. class SimpleCommand(
  2.     private val action: () -> Unit,
  3.     private val isEnabledPredicate: () -> Boolean = { true },
  4.     private val isVisiblePredicate: () -> Boolean = { true }
  5. ) : Command {
  6.     private val boundComponents = LinkedHashSet<Component>(1)
  7.    
  8.     private val listener = object : Property.ValueChangeListener, Container.ItemSetChangeListener, Button.ClickListener {
  9.         override fun valueChange(event: Property.ValueChangeEvent?) = refresh()
  10.        
  11.         override fun containerItemSetChange(event: Container.ItemSetChangeEvent?) = refresh()
  12.        
  13.         override fun buttonClick(event: Button.ClickEvent?) = execute()
  14.     }
  15.    
  16.     override fun execute() = when {
  17.         isEnabled -> action()
  18.         else -> throw IllegalStateException("Command is disabled")
  19.     }
  20.    
  21.     override val isEnabled: Boolean
  22.         get() = isEnabledPredicate()
  23.    
  24.     override val isVisible: Boolean
  25.         get() = isVisiblePredicate()
  26.    
  27.     private fun bindComponent(component: Component) {
  28.         if (boundComponents.add(component)) {
  29.             refreshComponent(component)
  30.         }
  31.     }
  32.    
  33.     private fun unbindComponent(component: Component) {
  34.         if (boundComponents.remove(component)) {
  35.             component.isEnabled = true
  36.             component.isVisible = true
  37.         }
  38.     }
  39.    
  40.     private fun refreshComponent(component: Component) {
  41.         component.isEnabled = isEnabled
  42.         component.isVisible = isVisible
  43.     }
  44.    
  45.     private fun refresh() {
  46.         for (component in boundComponents) {
  47.             refreshComponent(component)
  48.         }
  49.     }
  50.    
  51.     override fun bindNotifier(notifier: Property.ValueChangeNotifier) = notifier.addValueChangeListener(listener)
  52.    
  53.     override fun unbindNotifier(notifier: Property.ValueChangeNotifier) = notifier.removeValueChangeListener(listener)
  54.    
  55.     override fun bindNotifier(notifier: Container.ItemSetChangeNotifier) = notifier.addItemSetChangeListener(listener)
  56.    
  57.     override fun unbindNotifier(notifier: Container.ItemSetChangeNotifier) = notifier.removeItemSetChangeListener(listener)
  58.    
  59.     override fun bindButton(button: Button) {
  60.         button.addClickListener(listener)
  61.         bindComponent(button)
  62.     }
  63.    
  64.     override fun unbindButton(button: Button) {
  65.         button.removeClickListener(listener)
  66.         unbindComponent(button)
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement