Class: Teek::UI::EventBus
- Inherits:
-
Object
- Object
- Teek::UI::EventBus
- Defined in:
- lib/teek/ui/event_bus.rb
Overview
In-process publish/subscribe for decoupled app events (+:item_selected+,
:theme_changed) - not Tk events, complementary to
Handle#on_click/Handle#on_key. Reach for this only when a direct
handle or a shared reactive Var would couple things that should
stay decoupled.
Owned by one Session (+ui.on+/+ui.emit+/+ui.off+) - two separate app instances in the same process never share a bus. Pure Ruby, no Tk/interpreter involved, so it works before realize too.
Instance Method Summary collapse
-
#emit(event, *args, **kwargs) ⇒ void
Emit a named event to every current subscriber, in subscription order.
-
#initialize ⇒ EventBus
constructor
private
A new instance of EventBus.
-
#off(event, block) ⇒ void
Unsubscribe a specific listener.
-
#on(event) { ... } ⇒ Proc
Subscribe to a named event.
Constructor Details
#initialize ⇒ EventBus
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns a new instance of EventBus.
16 17 18 |
# File 'lib/teek/ui/event_bus.rb', line 16 def initialize @listeners = Hash.new { |h, k| h[k] = [] } end |
Instance Method Details
#emit(event, *args, **kwargs) ⇒ void
This method returns an undefined value.
Emit a named event to every current subscriber, in subscription order.
34 35 36 37 38 39 40 41 |
# File 'lib/teek/ui/event_bus.rb', line 34 def emit(event, *args, **kwargs) if kwargs.empty? @listeners[event].each { |listener| listener.call(*args) } else @listeners[event].each { |listener| listener.call(*args, **kwargs) } end nil end |
#off(event, block) ⇒ void
This method returns an undefined value.
Unsubscribe a specific listener.
47 48 49 50 |
# File 'lib/teek/ui/event_bus.rb', line 47 def off(event, block) @listeners[event].delete(block) nil end |
#on(event) { ... } ⇒ Proc
Subscribe to a named event.
24 25 26 27 |
# File 'lib/teek/ui/event_bus.rb', line 24 def on(event, &block) @listeners[event] << block block end |