Class: RubyEvent::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-event/event.rb

Instance Method Summary collapse

Constructor Details

#initialize(handlers = [], named_handlers = {}) ⇒ Event

Creates a new instance of event, optionally passing in an already created array of handlers for the event



14
15
16
17
18
19
20
# File 'lib/ruby-event/event.rb', line 14

def initialize(handlers = [], named_handlers = {})
  @handlers       = handlers
  @named_handlers = named_handlers
  
  @handlers_lock       = Mutex.new
  @named_handlers_lock = Mutex.new
end

Instance Method Details

#+(handler) ⇒ Object

Returns a new Event object with a new handler added,



23
24
25
26
27
# File 'lib/ruby-event/event.rb', line 23

def +(handler)
  @handlers_lock.synchronize do
    @handlers << handler
  end
end

#call(sender, args) ⇒ Object

Calls all of the handlers for the events, with the given sender and set of arguments.



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ruby-event/event.rb', line 46

def call(sender, args)
  # Make sure we don't get surprised with new friends while we're calling
  # the handlers
  named_handlers = @named_handlers
  handlers       = @handlers

  named_handlers.each do |name, handler|
    handler.call(sender, *args)
  end
  handlers.each do |handler|
    handler.call(sender, *args)
  end
end

#clear!Object

Clears the list of anonymous handlers



61
62
63
64
65
# File 'lib/ruby-event/event.rb', line 61

def clear!
  @handlers_lock.synchronize do
    @handlers       = []
  end
end

#subscribe(name, &block) ⇒ Object

Creates a new named handler (you can unregister these later without affecting other handlers)



31
32
33
34
35
# File 'lib/ruby-event/event.rb', line 31

def subscribe(name, &block)
  @named_handlers_lock.synchronize do
    @named_handlers[name] = block
  end
end

#unsubscribe(name) ⇒ Object

Removes a named handler from the event



38
39
40
41
42
# File 'lib/ruby-event/event.rb', line 38

def unsubscribe(name)
  @named_handlers_lock.synchronize do
    @named_handlers.delete(name)
  end
end