Class: Events
- Inherits:
-
Object
- Object
- Events
- Defined in:
- lib/ektoplayer/events.rb
Overview
Event class
Direct Known Subclasses
Instance Method Summary collapse
-
#auto_create ⇒ Object
Enables auto creation of non existent events.
-
#initialize(*known_events) ⇒ Events
constructor
Create a new events object.
-
#no_auto_create ⇒ Object
Disables auto creation of non existent events.
-
#on(event, &block) ⇒ Object
Register hook for event.
-
#on_all(&block) ⇒ Object
Forward all events to block(event, *args).
- #on_multi(*events, &block) ⇒ Object
-
#register(*events) ⇒ Object
(also: #reg)
Registers a new event.
-
#trigger(event, *args) ⇒ Object
Trigger event.
Constructor Details
#initialize(*known_events) ⇒ Events
Create a new events object
4 5 6 7 8 9 10 11 12 13 14 |
# File 'lib/ektoplayer/events.rb', line 4 def initialize(*known_events) @on_all = [] if known_events.empty? @map = {} auto_create else @map = known_events.map { |e| [e, []] }.to_h no_auto_create end end |
Instance Method Details
#auto_create ⇒ Object
Enables auto creation of non existent events
23 24 25 26 |
# File 'lib/ektoplayer/events.rb', line 23 def auto_create @map.default_proc = proc { |h,k| h[k] = [] } self end |
#no_auto_create ⇒ Object
Disables auto creation of non existent events
17 18 19 20 |
# File 'lib/ektoplayer/events.rb', line 17 def no_auto_create @map.default_proc = proc { |h,k| fail KeyError, "Unknown event: #{k}" } self end |
#on(event, &block) ⇒ Object
Register hook for event
35 36 37 38 |
# File 'lib/ektoplayer/events.rb', line 35 def on(event, &block) fail ArgumentError unless block @map[event] << block end |
#on_all(&block) ⇒ Object
Forward all events to block(event, *args)
45 46 47 48 |
# File 'lib/ektoplayer/events.rb', line 45 def on_all(&block) fail ArgumentError unless block @on_all << block end |
#on_multi(*events, &block) ⇒ Object
40 41 42 |
# File 'lib/ektoplayer/events.rb', line 40 def on_multi(*events, &block) events.each { |event| on(event, &block) } end |
#register(*events) ⇒ Object Also known as: reg
Registers a new event
29 30 31 |
# File 'lib/ektoplayer/events.rb', line 29 def register(*events) events.each { |event| @map[event] = [] } end |
#trigger(event, *args) ⇒ Object
Trigger event
51 52 53 54 55 56 57 58 59 |
# File 'lib/ektoplayer/events.rb', line 51 def trigger(event, *args) @on_all.each { |callback| callback.(event, *args) } if @map.key?(event) @map[event].each { |callback| callback.call(*args) } end rescue Ektoplayer::Application.log(self, 'event hook failed', $!) end |