Class: Teek::UI::EventBus

Inherits:
Object
  • Object
show all
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

Constructor Details

#initializeEventBus

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.

Parameters:

  • event (Symbol)
  • args (Array)

    forwarded to each subscriber

  • kwargs (Hash)

    forwarded to each subscriber



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.

Parameters:

  • event (Symbol)
  • block (Proc)

    the block #on returned



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.

Parameters:

  • event (Symbol)

Yields:

  • the subscriber, called with whatever #emit was given

Returns:

  • (Proc)

    the block, to pass to a later #off



24
25
26
27
# File 'lib/teek/ui/event_bus.rb', line 24

def on(event, &block)
  @listeners[event] << block
  block
end