Skip to content

Commit

Permalink
Add Eventable.off method to cancel callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
joelind committed Apr 4, 2013
1 parent d3a9a0e commit 186b373
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 8 deletions.
15 changes: 11 additions & 4 deletions README.md
Expand Up @@ -666,15 +666,22 @@ idiom it is available as a public API.

```ruby
> o = Class.new { include EM::Eventable }.new
=> #<#<Class:0x6dc1310>:0x6dc2ec0>
=> #<#<Class:0xab63f00>:0xab64430>
> o.on(:november_5_1955) { puts "Ow!" }
=> [#<Proc:0x6dc6300>]
> o.on(:november_5_1955) { puts "Flux capacitor!" }
=> [#<Proc:0x6dc6300>, #<Proc:0x6dc1ba0>]
=> [#<Proc:0xad9bf00>]
> flux = proc{ puts "Flux capacitor!" }
=> #<Proc:0xab630f0>
> o.on(:november_5_1955, &flux)
=> [#<Proc:0xad9bf00>, #<Proc:0xab630f0>]
> o.trigger(:november_5_1955)
Ow!
Flux capacitor!
=> [nil, nil]
> o.off(:november_5_1955, &flux)
=> #<Proc:0xab630f0>
> o.trigger(:november_5_1955)
Ow!
=> [nil]
```

# Suggestions?
Expand Down
18 changes: 14 additions & 4 deletions motion/reactor/eventable.rb
Expand Up @@ -7,18 +7,28 @@ module Eventable
# and be passed the arguments that are passed to
# `trigger`.
def on(event, &blk)
@events ||= Hash.new { |h,k| h[k] = [] }
@events[event].push blk
events[event].push blk
end

# When `event` is triggered, do not call the given
# block any more
def off(event, &blk)
events[event].delete_if { |b| b == blk }
blk
end

# Trigger an event
def trigger(event, *args)
@events ||= Hash.new { |h,k| h[k] = [] }
@events[event].map do |event|
events[event].map do |event|
event.call(*args)
end
end

private

def events
@events ||= Hash.new { |h,k| h[k] = [] }
end
end
end
end
15 changes: 15 additions & 0 deletions spec/motion/reactor/eventable_spec.rb
Expand Up @@ -15,6 +15,21 @@
events = @subject.instance_variable_get(:@events)
events[:foo].member?(proof).should == true
end

it 'returns the array of blocks for the event' do
proof = proc { }
@subject.on(:foo, &proof).should == [proof]
end
end

describe '.off' do
it 'unregisters events' do
proof = proc { }
@subject.on(:foo, &proof)
events = @subject.instance_variable_get(:@events)
@subject.off(:foo, &proof)
events[:foo].member?(proof).should == false
end
end

describe '.trigger' do
Expand Down

0 comments on commit 186b373

Please sign in to comment.