Sha256: f6b671c02586f49919c3b7969212aee81feabab990742290d22f231fb8d62bd4

Contents?: true

Size: 873 Bytes

Versions: 7

Compression:

Stored size: 873 Bytes

Contents

# o = Observer.new
# o.append('greet') {
#  puts 'hi'
# }
# o.call('greet')
#
# def greet(who)
#  puts "Hi #{who}"
# end
# o.append('greet', method(:greet), 'Alex')
# o.call('greet')

module Bowline
  class Observer
    def initialize
      @listeners = {}
    end
    
    # Append block/method to listeners
    def append(event, method = nil, *args, &block)
      (@listeners[event.to_s] ||= []) << [method||block, args]
    end
    
    # Like append, but adds it to the body too
    def on(event, method = nil, &block)
      append(event, method, &block)
      JQuery.bind(event.to_s, method(:call), event)
    end
    
    # Call event
    def call(event)
      event = event.to_s
      @listeners[event].each do |callback|
        callback[0].call(*callback[1])
      end
      @listeners.delete(event)
    end
  
    def clear
      @listeners = {}
    end
  end
end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
maccman-bowline-0.1.1 lib/bowline/observer.rb
maccman-bowline-0.1.2 lib/bowline/observer.rb
maccman-bowline-0.1.3 lib/bowline/observer.rb
maccman-bowline-0.1.4 lib/bowline/observer.rb
maccman-bowline-0.1.6 lib/bowline/observer.rb
maccman-bowline-0.1.7 lib/bowline/observer.rb
bowline-0.1.6 lib/bowline/observer.rb