Module: Watchable

Defined in:
lib/watchable.rb

Instance Method Summary collapse

Instance Method Details

#fire(event, *args) ⇒ Object



6
7
8
9
10
11
# File 'lib/watchable.rb', line 6

def fire event, *args
  watchers[event].each { |w| w.call *args        }
  watchers[:all].each  { |w| w.call event, *args }

  self
end

#off(event, callable = nil, &block) ⇒ Object



28
29
30
31
32
33
# File 'lib/watchable.rb', line 28

def off event, callable = nil, &block
  watcher = callable || block
  watcher ? watchers[event].delete(watcher) : watchers[event].clear

  self
end

#on(event, callable = Proc.new) ⇒ Object



13
14
15
16
17
# File 'lib/watchable.rb', line 13

def on event, callable = Proc.new
  watchers[event] << callable

  self
end

#once(event, callable = Proc.new) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/watchable.rb', line 19

def once event, callable = Proc.new
  wrapper = lambda do |*args|
    off event, wrapper
    callable.call *args
  end

  on event, wrapper
end

#watchersObject



2
3
4
# File 'lib/watchable.rb', line 2

def watchers
  @watchers ||= Hash.new { |h, k| h[k] = [] }
end