Module: Eventful

Extended by:
Eventful
Includes:
ObservableWithBlocks
Included in:
Eventful
Defined in:
lib/eventful.rb

Overview

Adds named event publishing capabilities to the class that includes it. Actually composed of three modules: Observable (from Ruby stdlib), ObservableWithBlocks, and Eventful itself. See README for examples.

Defined Under Namespace

Modules: ObservableWithBlocks Classes: Observer

Constant Summary collapse

VERSION =
'1.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ObservableWithBlocks

#add_observer

Class Method Details

.included(base) ⇒ Object

Classes that include Eventful are also extended with it, so that event listeners can be registered on a class to fire whenever an instance of that class publishes an event.



98
99
100
# File 'lib/eventful.rb', line 98

def self.included(base)
  base.extend(self)
end

Instance Method Details

#fire(*args) ⇒ Object

Fires a named event on the target object. The first argument should be a symbol representing the event name. Any subsequent arguments are passed listeners along with the publishing object. The event bubbles up the type system so that you can listen to all objects of a given type by regsitering listeners on their class.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/eventful.rb', line 79

def fire(*args)
  return self if defined?(@observer_state) and not @observer_state
  
  receiver = (Hash === args.first) ? args.shift[:receiver] : self
  args = [receiver] + args
  
  changed(true)
  notify_observers(*args)
  changed(true)
  
  args[0] = {:receiver => receiver}
  self.class.ancestors.grep(Eventful).each &it.fire(*args)
  
  self
end

#on(event, &block) ⇒ Object

Registers a named event handler on the target object that will only fire when the object publishes events with the given name. The handler should be a block that will accept the object that fired the event, along with and data published with the event. Returns a Methodphitamine::It instance that will be replayed on the publishing object when the event fires.

See README for examples.



64
65
66
67
68
69
70
71
72
# File 'lib/eventful.rb', line 64

def on(event, &block)
  observer = add_observer do |*args|
    type, data = args[1], [args[0]] + args[2..-1]
    if type == event
      block ||= observer.to_proc
      block.call(*data)
    end
  end
end