Skip to content

Instantly share code, notes, and snippets.

@lnznt
Created January 1, 2015 02:41
Show Gist options
  • Save lnznt/79d5eaaa62675e231a66 to your computer and use it in GitHub Desktop.
Save lnznt/79d5eaaa62675e231a66 to your computer and use it in GitHub Desktop.
Notifier.rb
#!/usr/bin/env ruby
module Notifier
attr_reader :listeners
def on(event, *xs, &b)
@listeners ||= Hash.new {|h,k| h[k] = []}
@listeners[event].push *xs, b
end
def off(event, &b)
listeners[event].delete_if &b
end
def notify(event, &b)
listeners[event].each &(b ? b : :call)
end
end
if __FILE__ == $0
class C
include Notifier
def foo
notify :foo
end
def bar(*args)
notify(:bar) {|x| x.(*args) }
end
end
c = C.new
c.on(:foo) { puts 'This is foo' }
px = -> { puts 'This is foo 2' }
c.on :foo, &px
c.on(:bar) {|x| puts "This is bar: #{x}" }
c.foo
c.bar 'hello'
c.off(:foo) {|x| x == px }
c.foo
end
# vi:set ts=2 sw=2 et:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment