Class: Cura::Event::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/cura/event/handler.rb

Overview

The event handler. Each Component as well as several other class’s instances have an instance of this handler. The handler can have multiple callbacks defined for an arbitrary event name.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host) ⇒ Handler

Returns a new instance of Handler.

Parameters:

Raises:

  • (TypeError)


14
15
16
17
18
19
# File 'lib/cura/event/handler.rb', line 14

def initialize(host)
  raise TypeError, "host must be a Cura::Attributes::HasEvents" unless host.is_a?(Cura::Attributes::HasEvents)
  
  @host = host
  @callbacks = { default: [] }
end

Instance Attribute Details

#callbacksHash<Symbol,Array> (readonly)

The callbacks defined on this handler. Key is the event name and the value is an Array of Proc instances.

Returns:

  • (Hash<Symbol,Array>)


30
31
32
# File 'lib/cura/event/handler.rb', line 30

def callbacks
  @callbacks
end

#hostObject (readonly)

Get the object this handler is attached to.

Returns:

  • (Object)


24
25
26
# File 'lib/cura/event/handler.rb', line 24

def host
  @host
end

Instance Method Details

#handle(event) ⇒ Object

Run all callbacks registered on this instance for the given event. The event object is given as a block argument to the callbacks. TODO: These should be able to break the callback chain by returning false in the callback (which would also break the delegation chain). TODO: The event should be delegated to the host’s #parent if there are no callbacks registered for it, if it responds to #parent, and it’s not nil.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/cura/event/handler.rb', line 43

def handle(event)
  callbacks = @callbacks[:default] + @callbacks[event.class.name].to_a
  
  chain_broken = false
  callbacks.each do |callback|
    
    result = host.instance_exec(event, *callback[:arguments], &callback[:block])
    
    # TODO: Optional event consumption
    if result == false
      # chain_broken = true # TODO TODO TODO TODO TODO 
      
      break
    end
    
  end
  
  delegate_event(event) unless chain_broken
end

#register(event_name = :default, *arguments, &block) ⇒ Object

Add a callback to the event chain. The first registered callback will be the first one called (FIFO). If no event_name is given, the callback is registered to the ‘:default` name, which are called before all others.



35
36
37
# File 'lib/cura/event/handler.rb', line 35

def register(event_name=:default, *arguments, &block)
  (@callbacks[event_name] ||= []) << { block: block, arguments: arguments }
end