Class: Octiron::Events::Bus
- Inherits:
-
Object
- Object
- Octiron::Events::Bus
- Includes:
- Support::Identifiers
- Defined in:
- lib/octiron/events/bus.rb
Overview
Implements and in-process pub-sub events broadcaster allowing multiple observers to subscribe to different events.
Instance Attribute Summary collapse
-
#default_namespace ⇒ String
readonly
The default namespace to search for events.
Instance Method Summary collapse
-
#clear ⇒ Object
Clears all event handlers.
-
#initialize(default_namespace = ::Octiron::Events) ⇒ Bus
constructor
A new instance of Bus.
-
#publish(event) ⇒ Object
(also: #broadcast, #notify)
Broadcast an event.
-
#subscribe(event_id, handler_object = nil, &handler_proc) ⇒ Object
(also: #register)
Subscribe an event handler to an event.
-
#unsubscribe(event_id, handler_object = nil, &handler_proc) ⇒ Object
Unsubscribe an event handler from an event.
Methods included from Support::Identifiers
Methods included from Support::Constantize
Methods included from Support::CamelCase
Constructor Details
Instance Attribute Details
#default_namespace ⇒ String (readonly)
Returns the default namespace to search for events.
22 23 24 |
# File 'lib/octiron/events/bus.rb', line 22 def default_namespace @default_namespace end |
Instance Method Details
#clear ⇒ Object
Clears all event handlers
34 35 36 |
# File 'lib/octiron/events/bus.rb', line 34 def clear @handlers = {} end |
#publish(event) ⇒ Object Also known as: broadcast, notify
Broadcast an event. This is an instance of a class provided to #subscribe previously.
77 78 79 80 81 82 83 84 85 |
# File 'lib/octiron/events/bus.rb', line 77 def publish(event) event_name = event if not event.is_a?(Hash) event_name = event.class.to_s end handlers_for(event_name, false).each do |handler| handler.call(event) end end |
#subscribe(event_id, handler_object = nil, &handler_proc) ⇒ Object Also known as: register
Subscribe an event handler to an event.
49 50 51 52 53 |
# File 'lib/octiron/events/bus.rb', line 49 def subscribe(event_id, handler_object = nil, &handler_proc) return with_handlers(event_id, handler_object, handler_proc) do |hlist, h| hlist << h end end |
#unsubscribe(event_id, handler_object = nil, &handler_proc) ⇒ Object
Unsubscribe an event handler from an event.
67 68 69 70 71 |
# File 'lib/octiron/events/bus.rb', line 67 def unsubscribe(event_id, handler_object = nil, &handler_proc) return with_handlers(event_id, handler_object, handler_proc) do |hlist, h| hlist.delete(h) end end |