Module: Potty::Events

Included in:
Widgets::Base
Defined in:
lib/potty/events.rb

Overview

A tiny event-emitter mixin so widgets can be wired together declaratively. Any includer gains ‘on`/`off`/`emit`. Widgets emit semantic events (`:change`, `:focus`, `:select`, `:press`, …) that a consumer subscribes to with blocks — letting a View stitch its pieces together without each widget needing a bespoke callback setter:

input.on(:change)  { |text| preview.text = text }
toggle.on(:change) { |on|   advanced.visible = on }
button.on(:press)  { app.pop_view }

‘on` returns self, so subscriptions chain. Multiple listeners per event are supported and fire in registration order.

Instance Method Summary collapse

Instance Method Details

#emit(event, *args) ⇒ Object

Fire an event to its listeners. Returns true if any listener ran.



33
34
35
36
37
38
39
# File 'lib/potty/events.rb', line 33

def emit(event, *args)
  list = (@listeners ||= {})[event.to_sym]
  return false if list.nil? || list.empty?

  list.each { |cb| cb.call(*args) }
  true
end

#listeners?(event) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
44
# File 'lib/potty/events.rb', line 41

def listeners?(event)
  list = (@listeners ||= {})[event.to_sym]
  !(list.nil? || list.empty?)
end

#off(event = nil) ⇒ Object

Remove listeners for one event, or all events when called bare.



26
27
28
29
30
# File 'lib/potty/events.rb', line 26

def off(event = nil)
  @listeners ||= {}
  event ? @listeners.delete(event.to_sym) : @listeners.clear
  self
end

#on(event, &block) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/potty/events.rb', line 17

def on(event, &block)
  return self unless block

  (@listeners ||= {})[event.to_sym] ||= []
  @listeners[event.to_sym] << block
  self
end